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

我想在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!

当前回答

 var counter = 0;
 var listArray = [0, 1, 2, 3, 4];
 function callBack() {
     if (listArray.length === counter) {
         console.log('All Done')
     }
 };
 listArray.forEach(function(element){
     console.log(element);
     counter = counter + 1;
     callBack();
 });

其他回答

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

使用异步NPM包。

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

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

在ES2018中,你可以使用异步迭代器:

const asyncFunction = a => fetch(a);
const itemDone = a => console.log(a);

async function example() {
  const arrayOfFetchPromises = [1, 2, 3].map(asyncFunction);

  for await (const item of arrayOfFetchPromises) {
    itemDone(item);
  }

  console.log('All done');
}

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

posts.forEach(function(v, i){
   res.write(v + ". Index " + i);
});
res.end();

在这个帖子中有许多解决方案和方法来实现这一点!

但是,如果你需要用map和async/await来做这个,那么这里就是

// Execution Starts
console.log("start")

// The Map will return promises
// the Execution will not go forward until all the promises are resolved.
await Promise.all(
    [1, 2, 3].map( async (item) => {
        await asyncFunction(item)
    })
)

// Will only run after all the items have resolved the asynchronous function. 
console.log("End")

输出将如下所示!可能根据异步函数而有所不同。

start
2
3
1
end

注意:如果你在map中使用await,它总是会返回promises数组。