正如标题所示。我怎么做呢?

我想在foreach循环遍历每个元素并完成一些异步处理后调用whenAllDone()。

[1, 2, 3].forEach(
  function(item, index, array, done) {
     asyncFunction(item, function itemDone() {
       console.log(item + " done");
       done();
     });
  }, function allDone() {
     console.log("All done");
     whenAllDone();
  }
);

有可能让它这样工作吗?当forEach的第二个参数是一个回调函数,当它经过所有迭代时运行?

预期的输出:

3 done
1 done
2 done
All done!

当前回答

我的解决方案:

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

例子:

var arr = ['a', 'b', 'c'];

arr.forEachDone(function(item){
    console.log(item);
}, function(){
   console.log('done');
});

// out: a b c done

其他回答

这是Node.js的异步解决方案。

使用异步NPM包。

(JavaScript)同步forEach循环内部回调

你不应该需要一个回调来迭代一个列表。只需在循环之后添加end()调用。

posts.forEach(function(v, i){
   res.write(v + ". Index " + i);
});
res.end();
//First Example
save() {
    this.holdImageData.forEach((val,i) => {
        this.UploadToMinio(val.file, val.index, res => {
            if (res && i+1 == this.holdImageData.length) {
                this.FinallySave();
            }
        })
    })
}

UploadToMinio(files, index, callback) {
    this._fileUploadService.uploadFile(files[0], files[0].name, 'rms').subscribe(data => {
        if (data) {
            console.log('data >>> ', data);
            callback(true);
        }
    })
}

FinallySave() {}

//Second Example
var sum = 0; // It can be global variable
startFunction() {
    this.sumFunction(2, 4, res => {
        if (res == true && sum == 6) {
            this.saveFunction();
        } else {
            //call to another function
        }
    })
}

sumFunction(num1, num2, callback) {
    if ((num1 + num2) == 6) {
        callback(true)
    }
    callback(false);
}

奇怪的是,异步情况下有多少错误的答案! 可以简单地表明,检查索引没有提供预期的行为:

// INCORRECT
var list = [4000, 2000];
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
    }, l);
});

输出:

4000 started
2000 started
1: 2000
0: 4000

如果我们检查index === array。长度- 1,回调将在第一次迭代完成时被调用,而第一个元素仍然悬而未决!

要在不使用async等外部库的情况下解决这个问题,我认为最好的方法是保存列表的长度,并在每次迭代后递减。因为只有一个线程,我们确定没有竞争条件的机会。

var list = [4000, 2000];
var counter = list.length;
list.forEach(function(l, index) {
    console.log(l + ' started ...');
    setTimeout(function() {
        console.log(index + ': ' + l);
        counter -= 1;
        if ( counter === 0)
            // call your callback here
    }, l);
});

我尝试简单的方法来解决它,分享给你:

let counter = 0;
            arr.forEach(async (item, index) => {
                await request.query(item, (err, recordset) => {
                    if (err) console.log(err);

                    //do Somthings

                    counter++;
                    if(counter == tableCmd.length){
                        sql.close();
                        callback();
                    }
                });

request是mssql库在Node js中的函数。这可以取代你想要的每个函数或代码。 古德勒克