I have a button which executes the following function when clicked :
async function VerifyData() {
if(condition1) {
MessageBox("Operation Not Allowed.");
return;
}
//Code to form the Ids is here
let result = await additionalCheck(Ids); //Passing Ids to Check
if(result) {
$("#Window").data("kendoWindow").open().center();
}
else {
return;
}
}
The additionalCheck(Ids) function is as follows :
function additionalCheck(Ids)
{
let count = 0;
return new Promise(resolve => {
$.ajax({
url: '@Url.Action("GetDetails", "Data")',
type: 'POST',
dataType: "text",
data: { ids: Ids },
success: function (data) {
isSuccess = true;
count = data;
},
error: function (x, y, z) {
isSuccess = false;
}
}).done(function () {
$.unblockUI();
if (isSuccess) {
if (count > 0) {
MessageBox("Operation Invalid.");
resolve(false); // This should prevent the verifyData() function also to terminate its execution
}
else {
resolve(true);//It should return to the previous function and execute the next line.
}
} else {
MessageBox("Error. Please try again.");
return;
}
});
});
}
The issue I am facing is when the additionalCheck(Ids) function is called, the code doesn't wait for the execution of the ajax statement in it and instead opens the Kendo Window before the function execution is completed.I want the VerifyData() function to wait for the additionalCheck(Ids) function execution before executing the statement after the call of the function.
I have tried using Promise but it didn't work for me (maybe I did not do it correctly).How can I achieve this?
To clarify things, javascript does wait for the execution of the additionalCheck function, but it will not wait for the completion of the ajax request, which is asynchronous, you will need to use a promise :
//Passing Ids to Check
additionalCheck(Ids).then(() => {
$("#Window").data("kendoWindow").open().center();
})
function additionalCheck(Ids)
{
return new Promise((resolve, reject) => {
let count = 0;
$.ajax({
url: '@Url.Action("GetDetails", "Data")',
type: 'POST',
dataType: "text",
data: { ids: Ids },
success: function (data) {
isSuccess = true;
count = data;
},
error: function (x, y, z) {
isSuccess = false;
}
}).done(function () {
$.unblockUI();
if (isSuccess) {
if (count > 0) {
MessageBox("Operation Invalid.");
reject();
}
else {
resolve();
}
} else {
MessageBox("Error. Please try again.");
reject();
}
});
})
}
but in that particular case like pointed out in the comments, its more simple to move the $("#Window").data("kendoWindow").open().center(); in the .done()