等到for循环中的所有函数调用结束执行 – Javascript

我有一个函数,其中包含一个for循环内的另一个函数调用。

outerFunction(){ for (var j = 0; j < geoAddress.length; j++) { innerFunction(j); } } 

我需要等到所有对innerFunction的调用完成。 如果我需要并行执行这些函数,那么如何在JavaScript中实现这一点?

看看asynchronous库。 https://www.npmjs.org/package/async

查看“while”的文档。 这听起来像它只是你所需要的。 同时(testing,FN,callback)

 var count = 0; async.whilst( function () { return count < 5; }, function (callback) { count++; setTimeout(callback, 1000); }, function (err) { // 5 seconds have passed } 

);

编辑 – 使用Q Promise库做节点的方式

如果您使用Q promise库,请尝试以下操作:

 outerFunction(){ var promises = []; for (var j = 0; j < geoAddress.length; j++) { deferreds.push(innerFunction(j)); } Q.all(promises).then(function(){ // do things after your inner functions run }); } 

即使你不使用这个特定的库,原理也是一样的。 一个应该有一个函数返回一个承诺,或者在Q.denodify方法中包含一个承诺,将所有的调用推送到一个承诺数组,将所有的数组传递给你的库的.when()(jQuery)或.all ()(Q Promise Library),然后使用.then()在所有的promise被parsing后做事情。

 outerFunction() { var done = 0; function oneThreadDone() { done++; if (done === geoAddress.length) { // do something when all done } } for (var j = 0; j < geoAddress.length; j++) { setTimeout(function() { innerFunction(j, oneThreadDone); }, 0); } } 

在inner_function里面调用oneThreadDone()函数(通过parameter passing参数)

如果你不想为此使用外部库,你可以创build一个scope对象,比如process ,跟踪有多less个innerFunction调用仍在等待,并在完成时调用outer callback cb

与此相关的一点是,您仍然可以获得asynchronous执行的好处,但只要确保代码不会执行下一个部分,直到属于outerFunction的所有innerFunction实际完成为止:

 outerFunction(function() { console.log("All done for outerFunction! - What you should do next?"); // This block is executed when all innerFunction calls are finished. }); 

JavaScript的:

 // Example addresses var geoAddress = ["Some address X", "Some address Y"]; var innerFunction = function(geoAddress, process) { // Your work to be done is here... // Now we use only setTimeout to demonstrate async method setTimeout(function() { console.log("innerFunction processing address: " + geoAddress); // Ok, we update the process process.done(); }, 500); }; var outerFunction = function(cb) { // Process object for tracking state of innerFunction executions var process = { // Total number of work ahead (number of innerFunction calls required). count: geoAddress.length, // Method which is triggered when some call of innerFunction finishes done: function() { // Decrease work pool this.count--; // Check if we are done & trigger a callback if(this.count === 0) { setTimeout(cb, 0); } } }; for (var j = 0; j < geoAddress.length; j++) { innerFunction(geoAddress[j], process); } }; // Testing our program outerFunction(function() { console.log("All done for outerFunction! - What you should do next?"); // This block is executed when all innerFunction calls are finished. }); 

输出:

 innerFunction processing address: Some address X innerFunction processing address: Some address Y All done for outerFunction! - What you should do next? 

这里是js小提琴的例子

干杯。