我在调用web服务的控制器中使用$ http get来检索一些数据。这是下面的代码:JavaScript - 减速循环
UPDATE码:
var boolGetBoothCoords = false;
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)
.then(function(response) {
var data = response.data
console.log('data', data.arrBoothDesignatedCoords)
boothDesignatedCoords = data.arrBoothDesignatedCoords;
boolGetBoothCoords = true;
})
console.log("boothDesignatedCoords ", boothDesignatedCoords); // undefined
// And a lot of other codes
然而,由于$ HTTP GET是异步方法,程序将立即boothDesignatedCoords是未定义后调用控制台日志和代码。我不要那个。我希望程序在Web服务使用完成后调用控制台日志和代码。所以我做了以下使用这样的回答:how to slow down a javascript loop:
go();
function go() {
console.log("hello");
if (boolGetBoothCoords == false) {
setTimeout(go, 1000);
}
else
{
}
}
go()
console.log("boothDesignatedCoords ", boothDesignatedCoords); // undefined
// OTHER CODES that uses variable boothDesignatedCoords will be undefined as well
不过,我不知道为什么它仍然会调用控制台日志,但Web服务消费还没有完成,尽管使用这种方法。有人可以帮帮我吗?谢谢。
为什么不在'fnProceedOtherTask1()'调用的最后'then'回调中包含'console.log'? – andrusieczko
对不起,感到困惑。我仍然更新了我的问题 – Antoni
,最好在最后一次回调中打印它比等待使用'setTimeout'更好...如果服务器响应时间超过1秒会发生什么?它仍然是undefined – andrusieczko