Reputation: 149
I have a function in javascript that runs another function and it should wait for the called function to complete its execution and return control back to the calling function. However, this doesn't happen and after called function starts executing, the calling function doesn't wait and falls right through.
function ButtonClick() {
AskQuestion(param1, param2, function (success) {
if (success == true) {
//do some staff here
}
}
}
function AskQuestion(param1, param2) {
//here I present a dialog box and ask users to fill it out, then I
//validate their entry. If it's validated then I do: `return true` and
//if it's not: `return false`
}
Right after I call AskQuestion function, it doesn't wait and success
will always be FALSE
What am I doing wrong here?
Upvotes: 0
Views: 323
Reputation: 21
As Gregory pointed out you should probably call the callback somewhere in your code passing the result of the result you want and then processing it in the callback.
But it depends on what you're using to present a dialog box. For example window.prompt() stops the execution of the JavaScript until the user gives a feedback.
function giveMeYouName() {
var name = prompt('Could you please give me your name?');
console.log('Your name is: ' + name);
}
giveMeYouName();
Name is printed only after you submit the prompt.
Upvotes: 0
Reputation: 348
To pass a callback to AskQuestion, the function has to accept a callback, and actually call that back if the asynchronous tasks are done:
function ButtonClick() {
AskQuestion(param1, param2, function (success) { // This anonymous function will be called at the end of the AskQuestion execution
if (success == true) {
//do some staff here
}
});
}
function AskQuestion(param1, param2, callback) {
//here I present a dialog box and ask users to fill it out, then I
//validate their entry. If it's validated then I do: `return true` and
//if it's not: `return false`
callback(success); // assuming success is a variable set to true if no problem happened
}
Upvotes: 2