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

140
Views
Looping through array and update variable based on async code

I am trying to loop through an array and calling a promise, and based on that result it updates the variable. The code is working as I wanted but I am concerned if this is a good way to write it. Are there any better ways? Thank you in advance.

/**
*
* u/returns Resolves a promise and returns value 'b'
*/
async function generatePromise() {
   return Promise.resolve('b');
}

async function main() {
   let showWarning = false;
   // List of users
   const users = ['a', 'b', 'c'];
   //Looping through users array and compare the result from promise and update showWarning boolean
   await users.reduce(async (promise, user) => {
     await promise;
     const result = await generatePromise();
     if (result === user) showWarning = true;
   }, Promise.resolve())

   console.log(showWarning)
}
main();
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Seems unnecessarily complicated and the logic is somewhat backwards. Assuming that generatePromise will always return the same response, why would you call it multiple times? Call it once and check whether the value is contained in the array:

const showWarning = users.includes(await generatePromise());

If the function needs to be called multiple times (e.g. because it could potentially return a different response per input/user) then you can use a simple for loop:

for (const user of users) {
  if (user === await generatePromise()) {
    showWarning = true;
    break; // why check other users if `showWarning` won't change anymore?
  }
}
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!