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

154
Views
How to asynchronously process a dynamically sized array dependent on the fetch responses?

The following code works but is slow because I need to await each response instead of asynchronously processing the responses as they come in.

I imagine there is a way to do this with promises.all() but can't come up with a solution.

  let relatives = [ancestor];
  while (relatives.length > 0) {
    const nextRelative = relatives.pop();
    await fetchRelatives(nextRelative).then(relative => {
      relatives = relatives.concat(relative.ancestors);
    });
  }

We can assume the order is not important, as long as we process the entire tree.

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

0

You can use promises:

Promise.all( relatives.map( task => fetchRelatives(task) ) ).then( results => {
    console.log('all responses:', results)
})

Or

var results = await Promise.all( relatives.map( task => fetchRelatives(task) ) )

if relatives is added dynamically, then this should work:

var do_task = async( relative ) => {
    if (relative) 
        relatives.push(... relative.ancestors)
    
    if (relatives.length)
        return fetchRelatives( relatives.pop() ).then( person => do_task( person ) )
}

/// 4 workers:
Promise.all( Array(4).fill().map( do_task ) ).then(() => console.log('all done'))
about 4 years ago · Juan Pablo Isaza Report

0

if The order of the answers is important to you. You have no choice but to use the async/await or generator functions.

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!