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.
Using Promise.all()Promise.all waits for all fulfillments (or the first rejection).
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With