一种方法来知道什么时候所有的callback是在JavaScript中完成的

我有很多调用服务的最后,我想写一个文件我的最后收集服务的所有callback已经返回。 有没有办法确保所有的callback都完成了?

for (id in idsCollection) { object.callService(id, function (res) { collection.push(res); }); } filewriter.writetoFile("filename.json", JSon.Stringify(collection)); 

编辑:只是logging我用nodeJS cheerio。

创build一个数组。 每次设置callback时,都会将某些东西推到数组上。 每次callback运行时都会popup一些东西。 检查callback函数内数组是否为空。 如果它是空的,那么所有的callback都完成了。

你可以简单的数一下。 在你的情况下,似乎你已经知道将会有多lesscallback。

 var remaining = idsCollection.length; // assuming array for (id in idsCollection) { object.callService(id, function (res) { collection.push(res); remaining -= 1; // decrement by 1 per callback // here you can check if remaining === 0 (all done) }); } 

我通常使用节点asynchronous库这种事情。 它可以很容易地完成你正在谈论的内容:

 async.each(yourArray, function(element, next) { // this callback gets called for each element in your array element.doSomething(function(returnValue){ next(returnValue) // call next when you're done } }, function(err, returnValues) { // when all the elements in the array are processed, this is called if (err) return console.log(err); console.log(returnValues) // this is an array of the returnValues }); }) 

jQuery.Deferred()对象可能是你在找什么。

或者如果您使用HTML5,则可以使用promises

以下是如何创build承诺

 var promise = new Promise(function(resolve, reject) { // do a thing, possibly async, then… if (/* everything turned out fine */) { resolve("Stuff worked!"); } else { reject(Error("It broke")); } }); 

这里是如何使用它们

 promise.then(function(result) { console.log(result); // "Stuff worked!" }, function(err) { console.log(err); // Error: "It broke" }); 

检查此链接了解更多信息

你可以使用灵活的lib http://caolan.github.io/nimble/

灵活的平行例子

 var _ = require('nimble'); _.parallel([ function (callback) { setTimeout(function () { console.log('one'); callback(); }, 25); }, function (callback) { setTimeout(function () { console.log('two'); callback(); }, 0); } ], function(){ console.log('done') }); 

产量

 > two > one > done 

如果您使用jQuery,则可以使用$.when

例:

 exmCall1 = $.getJson(..); exmCall2 = $.getJson(..); $.when(exmCall1, exmCall2).done(function (exmCall1Ret, exmCall2Ret) { //do stuff }); 

你可以在这里阅读实际的文档: http : //api.jquery.com/jquery.when/

或者做一些硬编码:

  var running; for (id in idsCollection) { object.callService(id, function (res) { collection.push(res); running += 1; }); } var loop = setInterval(function() { if(running >= idsCollection.length) { filewriter.writetoFile("filename.json", JSon.Stringify(collection)); clearInterval(loop); } , 500);