Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async functions not waiting inside a forEach loop


I have a call to my async function inside a forEach loop, like this:

foo {
    list.forEach(function( field ) {        
        populateValues( field );
    });

    // here my list is returned incomplete
    return list;
}

populateValues = async function ( field ) {
    if ( field.someProp === true ) {
        fields.val = await somePromise();
    }
}

somePromise = function() {
    return new Promise( resolve => {
        fetchMyAPIExample().then( function( value ) {
            resolve( value );
        }
    }
}

populateValues() waits correctly my promise, but foo() doesn't wait populateValues to return the list, so it return my list incomplete.

like image 621
Elzio Jr Avatar asked Jan 03 '23 16:01

Elzio Jr


2 Answers

You may want to await there too, which doesnt work with forEach but with for..of :

async function foo(){
  for(var field of list){        
    await populateValues( field );
  }
  return list
}

Or if you want to enable racing:

function foo(){
  return Promise.all(
    list.map( field => populateValues( field ))
  ).then(_=>list);
}
like image 100
Jonas Wilms Avatar answered Jan 14 '23 14:01

Jonas Wilms


Being that each of the function calls to populateValues() is async, the function foo doesn't wait to return the list object.

You can make foo await the results of populateValues to get the response you expect.

like image 29
ITDerrickH Avatar answered Jan 14 '23 14:01

ITDerrickH