Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for array.map iterations in Promise.all [duplicate]

I have the following code that should add items for customers if they dont already exist. Execution should be in parallel.

await Promise.all(
    customers.map(async (customer) => {
        return customer.items.map(async (item) => {
            return new Promise(async (resolve) => {
                const productExists = someArray.some(
                    (arrayValue) => arrayValue === item.id
                );
                if (!productExists) {
                    logger.info(
                    `customer item ${item.id} does not exist, creating...`
                    );
                    await createCustomerItem(item.id);
                    logger.info(`customer item ${item.id} created.`);

                    someArray.push(item.id);
                } else {
                    logger.info(`customer item ${item.id} already exists, skipping...`);
                }
                resolve(true);
            });
        });
    })

);

logger.info(`All items should now be present`);

The problem is that the execution is not waiting for createCustomerItem to resolve in the cases of !productExists)

This is the log

customer item 32310 does not exist, creating...
customer item ao does not exist, creating...
customer item ute does not exist, creating...
All items should not be present
customer item ao created.
customer item ute created.
customer item 32310 created.

Naturally All items should not be present should come last.

When all the items already exist, then the process looks good.

like image 505
AngularDebutant Avatar asked Nov 06 '22 03:11

AngularDebutant


People also ask

Does promise all wait for all promises?

Using Promise.all()Promise.all waits for all fulfillments (or the first rejection).

Can we use await with promise all?

all() with async-await. Example 1: In this example we will creating two promises inside two different functions (or methods) and in another function we will accessing them using Promise. all() along with making that function as async and promise resulting fetching will be done along with the await keyword.

Does map function return promise?

map(async ) returns an array of promises – one for each value in inputArray . Putting Promise. all() around the array of promises converts it into a single promise. The single promise from Promise.

How do you resolve promises on a map?

Combining And Resolving all Promises with Promise. all() , map() and Async/Await. So the first promise will be resolved then all the promises returned from the getProductId() for each product and then finally all the promises returned from capitalizeId() for each ID returned from the previous promises.


1 Answers

you can do something like this

const fruitsToGet = ['apple', 'grape', 'pear']

const mapLoop = async () => {
  console.log('Start')

  const promises = await fruitsToGet.map(async fruit => {
    const numFruit = new Promise((resolve, reject) => {
      setTimeout(() => resolve(fruit), 1000)
    });
    return numFruit
  })
  const numFruits = await Promise.all(promises)
  console.log(numFruits)

  console.log('End')
}

mapLoop();

results

Start
["apple", "grape", "pear"]
End

source demo

like image 123
Shashan Sooriyahetti Avatar answered Nov 12 '22 20:11

Shashan Sooriyahetti