我在 javascript 中有一个函数,它运行另一个函数,它应该等待被调用函数完成其执行并将控制权返回给调用函数。但是,这种情况不会发生,并且在被调用函数开始执行后,调用函数不会等待并直接执行。
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`
}
在我调用 AskQuestion 函数后,它不会等待,并且 success
将始终为 FALSE
我在这里做错了什么?
最佳答案
要将回调传递给 AskQuestion,该函数必须接受回调,并在异步任务完成时实际回调该回调:
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
}
关于Javascript 暂停执行并等待被调用函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51970087/