(JavaScript) Synchronizing forEach Loop with callbacks inside

前端 未结 5 2131
无人及你
无人及你 2020-12-08 02:24

I am doing some computations inside a double forEach Loop something like this:

array.forEach(function(element){
    Object.keys(element).forEach         


        
5条回答
  •  再見小時候
    2020-12-08 03:12

    You can wrap your callbacks in a count-down closure:

    var len = array.length;
    
    function countdownWrapper(callback, callbackArgs) {
        callback(callbackArgs);
        if (--len == 0) {
            someFunctionHere();
        }
    }
    
    array.forEach(function(element){
        Object.keys(element).forEach(function(key){
    
            var wrappedCallback = countdownWrapper.bind(callback);
            /* some complex computations with asynchronous WRAPPED callbacks  */
    
        });
    });
    

    If the call-backs have different number of arguments, you can do a little surgery on arguments instead of using an explicit callbackArgs parameter.

    EDIT Your edit clarifies that you want to start each complex computation after the previous calculation completes it's callback. This can also be easily arranged through closures:

    function complexOp(key, callback) { /* . . . */ }
    
    function originalCallback(...) { /* . . . */ }
    
    function doSomethingElse() { /* . . . */ }
    
    var iteratorCallback = (function (body, callback, completion) {
        var i = 0, len = array.length;
        return function iterator() {
            callback.apply(null, arguments);
            if (++i < len) {
                body(array[i], iterator);
            } else {
                completion();
            }
        };
    }(complexOp, originalCallback, doSomethingElse)); 
    
    // kick everything off:
    complexOp(array[0], iteratorCallback);
    

提交回复
热议问题