Asynchronous functions don't wait inside a forEach loop


I have a call to my async function inside a forEach loop, for example:

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 for my promise correctly, but foo () doesn't wait for populateValues ​​to return the list, so it returns my list incomplete.

+3


source to share


2 answers


You might want to wait too, which doesn't work with forEach, but with .of:

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

      



Or if you want to enable races:

function foo(){
  return Promise.all(
    list.map( field => populateValues( field ))
  ).then(_=>list);
}

      

+3


source


Since each function calls populateValues ​​() is asynchronous, foo does not wait for the list object to return .



You can make foo expectation of results populateValues , to get the answer you expect.

+3


source







All Articles