Reputation: 943
I'm working with promises and I need to know the result of all the items processed by an async method. So I thought that a Promise.all() would solve my problem like this:
const values = await Promise.all(items.map((item) => {
asyncMethodThatLogsAndReturnsBoolean(item);
}));
console.log(values);
What I find here is that some logs of the async method are printed after the values log. And values
is printed as an array of undefined
.
Is there any reason why this implementation is not waiting until all promises are resolved so the values object can be printed with the correct data?
*The asyncMethodThatLogsAndReturnsBoolean(item)
calls other async methods, but all calls have await
.
Upvotes: 2
Views: 4168
Reputation: 4748
The callback function inside map
needs to return a promise.
const values = await Promise.all(items.map((item) => {
return asyncMethodThatLogsAndReturnsBoolean(item);
}));
Otherwise, by not explicitly returning anything, you're only returning undefined
, which has Promise.all
assume that the element in the mapped array has successfully "resolved" to undefined
, which is not what you intended.
Upvotes: 10