以下代码不是异步的,为什么以及如何制作呢?
function compute(callback){
for(var i =0; i < 1000 ; i++){}
callback(i);
}
我将假设你的代码试图说,“我需要做1000次,然后在一切都完成时使用我的回调” .
即使你的for循环也不会在这里工作,因为想象一下:
function compute(callback){
for(var i =0; i < 1000 ; i++){
DatabaseModel.save( function (err, result) {
// ^^^^^^ or whatever, Some async function here.
console.log("I am called when the record is saved!!");
});
}
callback(i);
}
在这种情况下,你的for循环将执行保存调用,而不是等待它们完成 . 因此,在您的示例中,您可能会得到类似的输出(取决于时间)
I am called when the record is saved
hii
I am called when the record is saved
...
对于你的计算方法,只有当一切都真正完成时才调用回调 - 所有1000条记录都保存在数据库中 - 我会查看async Node包,它可以很容易地为你做到这一点, and 为你提供许多异步问题的模式我将面对Node .
所以,你可以重写你的计算功能:
function compute(callback){
var count = 0
async.whilst(
function() { return count < 1000 },
function(callback_for_async_module) {
DatabaseModel.save( function (err, result) {
console.log("I am called when the record is saved!!");
callback_for_async_module();
count++;
});
},
function(err) {
// this method is called when callback_for_async_module has
// been called 1000 times
callback(count);
);
console.log("Out of compute method!");
}
请注意,您的计算函数的回调参数将在 console.log("Out of compute method") 之后的某个时间被调用 . 此函数现在是异步的:应用程序的其余部分不会等待 compute 完成 .