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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With