噩梦般的功能要在所有代码运行之前完成。我试图建立一个计数器,并且仅在代码完成后返回。
我已经这样模拟了(我知道这并不妙,但是如果有人可以指出我的正确立场,我将不胜感激):
//I want this to alert "Done"
alert(timerCheck());
function timerCheck() {
var finished;
var myLoop = 5;
for (i = 0; i < myLoop; i++) {
//This is emulating the slow code
window.setTimeout(checkFinished, 900);
alert(i);
}
function checkFinished() {
//I originally had the "return here, before realising my error
finished = true;
}
if (finished) {
//This is where my problem is
return "done";
}
}
就像我说的那样,这是一个非常简化的示例-如果有人可以指出错误,那将为我省去很多麻烦!
最佳答案
如果该函数调用并依赖于异步函数,则无法同步获取该函数的返回值。
您必须使用回调。有关更多详细信息,请参见this question。
例如,您的函数将如下所示:
// pass a callback which gets the result of function
timerCheck(function(result) {
alert(result);
});
function timerCheck(callback) {
var myLoop = 5,
j = 0;
for (var i = 0; i < myLoop; i++) {
// This is emulating the slow code
// this will invoke `checkFinished` immediately,
// after 900ms, after 1800ms, after 2700ms and after 3600ms
window.setTimeout(checkFinished, i * 900);
}
function checkFinished() {
j++;
// after checkFinish was called 5 times, we invoke the callback
if(j === 5) {
callback('done');
}
}
}
关于javascript - Javascript循环-等待值(value),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10740042/