Callback after all asynchronous forEach callbacks are completed

后端 未结 13 2247
谎友^
谎友^ 2020-11-22 12:56

As the title suggests. How do I do this?

I want to call whenAllDone() after the forEach-loop has gone through each element and done some asynchronous p

13条回答
  •  一个人的身影
    2020-11-22 13:21

    My solution:

    //Object forEachDone
    
    Object.defineProperty(Array.prototype, "forEachDone", {
        enumerable: false,
        value: function(task, cb){
            var counter = 0;
            this.forEach(function(item, index, array){
                task(item, index, array);
                if(array.length === ++counter){
                    if(cb) cb();
                }
            });
        }
    });
    
    
    //Array forEachDone
    
    Object.defineProperty(Object.prototype, "forEachDone", {
        enumerable: false,
        value: function(task, cb){
            var obj = this;
            var counter = 0;
            Object.keys(obj).forEach(function(key, index, array){
                task(obj[key], key, obj);
                if(array.length === ++counter){
                    if(cb) cb();
                }
            });
        }
    });
    

    Example:

    var arr = ['a', 'b', 'c'];
    
    arr.forEachDone(function(item){
        console.log(item);
    }, function(){
       console.log('done');
    });
    
    // out: a b c done
    

提交回复
热议问题