Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
Can I rewrite for-of loop to Promise.all?

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)?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!