简体   繁体   English

等待直到for循环内的所有函数调用结束执行-Javascript

[英]Wait until all the function calls inside for-loop ends its execution - Javascript

I have a function which contains another function call inside a for loop. 我有一个函数,该函数在for循环中包含另一个函数调用。

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

I need to wait till all the calls to innerFunction is complete. 我需要等到对innerFunction的所有调用完成。 If I need parallel execution of these functions, how to achieve this in JavaScript? 如果需要并行执行这些功能,如何在JavaScript中实现呢?

Check out the async library. 检出异步库。 https://www.npmjs.org/package/async https://www.npmjs.org/package/async

Check out the documentation on "whilst". 查阅有关“ whilst”的文档。 It sounds like it does just what you need. 听起来它确实可以满足您的需求。 whilst(test, fn, callback) while(test,fn,callback)

var count = 0;

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

); );

Edit - Doing Things the Node Way Using Q Promise Library 编辑-使用Q Promise库以节点方式进行操作

If you're using the Q promise library, then try the following: 如果您使用的是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 
    });
}

Even if you're not using this particular library, the principle is the same. 即使您没有使用这个特定的库,原理也是一样的。 One should have one's function return a promise or have it wrapped in a promise as in the Q.denodify method, push all calls to an array of promises, pass said array to your library's equivalent of .when() (jQuery) or .all() (Q Promise Library) and then use .then() to do things after all promises are resolved. 应该像Q.denodify方法那样,使函数返回一个Promise或将其包装在Promise中,将所有调用推入一个Promise数组,然后将该数组传递给您的库中相当于.when()(jQuery)或.all的等效项。 ()(Q Promise Library),然后在所有的诺言都解决后,使用.then()进行操作。

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);
    }
}

and inside inner_function call oneThreadDone() function (reference passed throught param) 并在inner_function内部调用oneThreadDone()函数(通过参数传递的引用)

If you don't want to use external library for this you could make a scope object such as process which keeps track of how many innerFunction calls are still pending, and calls outer callback cb when it is finished. 如果您不想为此使用外部库,则可以创建一个范围对象,例如process ,它跟踪仍在等待中的innerFunction调用的数量,并在完成时调用外部回调cb

The point with this is that you still get the benefits of async execution, but you just make sure that your code won't execute the next part until all innerFunction belonging to outerFunction are actually finished: 这样做的目的是,您仍然可以获得异步执行的好处,但是您只需确保在属于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: 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.

});

Output: 输出:

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

Here is js fiddle example 这是js小提琴的例子

Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 For 循环是否处理表达式中的函数直到循环结束? - Does a For-loop process a function inside the expression until the loop ends? for循环应如何等待直到其中的函数完成了在angularjs中的执行? - How a for loop should wait until a function inside it finish its execution in angularjs? JavaScript如何等待函数及其所有子函数完成 - JavaScript how to wait until a function and all its child functions are done JavaScript 等待所有异步调用完成 - JavaScript Wait until all async calls finish for循环可以等到其中的功能完成执行吗? - Can a for-loop wait until a function within it has finished executing? 等待回调结束以继续在Angular中执行 - Wait until a callback ends to continue execution in Angular 去抖动的函数调用已延迟,但全部在等待计时器结束时执行 - Debounced function calls delayed but all executed when wait timer ends 如何等待直到由forEach循环执行的所有递归函数调用完成 - How to wait until all recursive function calls executed by forEach loop are finished Javascript等待Promise在for循环内完成,然后返回响应 - Javascript wait for Promise to complete inside for-loop before returning response nodejs等待循环完成所有MongoDB调用 - nodejs wait until all MongoDB calls in loop finish
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM