[英]JavaScript: How to return an outer function inside an asynchronous inner function?
I know I can use an external variable to identify some status the outer function needs to do with. 我知道我可以使用外部变量来识别外部函数需要处理的某些状态。 But consider this: If the inner function is asynchronous?
但请考虑一下:如果内部函数是异步的? The outer function will not wait for the variable of inner function will change, so how can I return the outer function now?
外部函数不会等待内部函数的变量会改变,那么我现在如何返回外部函数呢?
function outer() {
var flag = true;
// For example, a jquery-like ajax call
$.ajax({
// Some settings
error: function(jqXHR, textStatus, errorThrown) {
// Here I want to return outer()
flag = false;
}
});
return flag;
}
So as you can see, if I use flag
as the return value, outer()
will very likely return true because the ajax call may take a long time. 所以你可以看到,如果我使用
flag
作为返回值, outer()
很可能会返回true,因为ajax调用可能需要很长时间。 And for the same reason, I don't want to set async: false
because that will stop the page reaction. 出于同样的原因,我不想设置
async: false
因为这会停止页面反应。
Your outer
function will return immediately, so you will always get true
as flag
's value. 你的
outer
函数会立即返回,所以你总会得到true
作为flag
的值。 In order to get the right value, you need to let the async function do its job and get back to you when it is ready. 为了获得正确的值,您需要让异步函数完成其工作并在准备就绪时回复您。 Consider this:
考虑一下:
function outer(cb) {
var flag = true;
// For example, a jquery-like ajax call
$.ajax({
// Some settings
error: function (jqXHR, textStatus, errorThrown) {
// Here I want to return outer()
flag = false;
cb(flag);
},
success: function () {
flag = true; // or whatever value you need.
cb(flag);
}
});
}
function callback(flag) {
// this function will be called after the ajax is complete.
// real value of flag variable will be available here
console.log(flag);
}
outer(callback);
You pass a function as a parameter to outer function, and it calls that function when ajax is complete with the value you need as a parameter. 将函数作为参数传递给外部函数,并在ajax完成时使用您需要的值作为参数调用该函数。 This way you will get the real result.
这样你就可以得到真实的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.