简体   繁体   中英

Return end of Promise when every async function in a ForEach loop has been processed [Javascript/Typescript]

I have a ForEach loop in which I call an asynchronous function. With a counter, I can figure out when all the items in my array have been processed, but what I'd like to know, is how can I return my Promise as resolved when all the items have been processed ?

public doAsyncThingsToArray(array: number[]): Promise<void>
let count: number;
array.forEach((item) => {
    this.doAsynchStuff(item)
})
.then(() => {
    count++;
    if (count == item.length) {
        //Probably something has to be done here
    }
});

I want to be able to call my function doAsyncThingsToArray like this :

    doAsyncThingsToArray(myArray)
    .then(() => {
    //all my array has been processed
    })

Thank you !

EDIT :

The code below works

public doAsyncThingsToArray(array: number[]): Promise<void> {

Promise.all(
    array.map((item) => {
        return this.doAsynchStuff(item)
            .then(() => {
                console.log("item processed");
                return Promise.resolve();
            })
    })
)
.then(() => {
  console.log("All item are processed");
  return Promise.resolve();
});

This is why Array#map() and Promise.all() exist. Do not use Array#forEach() when you need a reference to each array item's promise. The body of doAsyncThingsToArray() should look like:

return Promise.all(array.map((item) => this.doAsyncStuff(item))

Where this.doAsyncStuff() returns a promise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM