I have a piece of code that loops through the array of users and filters them out based on a particular property. After that, I push user ids to a separate array.
Example:
// User's props:
// user: { id, name, subscriptions, isSubscribed: () => {} }
const userIds = []
for (const user of users) {
const isSubscribed = await user.isSubscribed(category)
if (isSubscribed) {
userIds.push(user.id)
}
}
I am wondering if such a sequential code could be rewritten to a parallel (with Promise.all for example)?
After the isSubscribed call, chain on the user.id if they're subscribed, otherwise undefined (or some other value distinguishable from an actual ID) so that that's what an individual Promise resolves to. Then filter the array for only values that are IDs.
const userIds = (await Promise.all(
users.map(
user => user.isSubscribed(category)
.then(isSubscribed => isSubscribed ? user.id : undefined)
)
))
.filter(userId => userId !== undefined);