Home > Blockchain >  How to asynchronously process a dynamically sized array dependent on the fetch responses?
How to asynchronously process a dynamically sized array dependent on the fetch responses?

Time:06-02

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.

CodePudding user response:

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

CodePudding user response:

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'))
  • Related