Skip to content

Instantly share code, notes, and snippets.

@NRDay
Created September 3, 2020 09:20
Show Gist options
  • Save NRDay/f72928b283e5bd2cfb28af082237cc72 to your computer and use it in GitHub Desktop.
Save NRDay/f72928b283e5bd2cfb28af082237cc72 to your computer and use it in GitHub Desktop.
Promises in forEach loop
// Create any artists that are not in the DB and return complete array of all artists
export function createArtists(artists) {
var updatedArtists = [];
return new Promise( function( resolve, reject ) {
artists.forEach( artist => {
if (! artist.id) {
// If the artist has no id - create it
createArtist( artist.name, artist.slug ).then( created => {
//Push to array
updatedArtists.push({
id: created.id,
name: created.name,
slug: created.slug
});
});
} else {
// If the artists does have id, push to array
updatedArtists.push({
id: artist.id,
name: artist.name,
slug: artist.slug
});
}
});
resolve( updatedArtists, console.log('create updatedArtists', updatedArtists) );
});
}
// WP REST API / Backbone
function createArtist( name, slug ) {
return new Promise( function( resolve, reject ) {
var created = '';
var artist = new wp.api.models.Itl_artists( {
name: name,
slug: slug
} );
created = artist.save();
resolve( created );
});
};
// Parse the data
parseData() {
// Get current artists
getCurrentArtists()
// Set currentArtists as this.state.currentArtists
.then( currentArtists => this.setCurrentArtistsState( currentArtists )
// Parse Artists from Table Data
.then( getNewArtists( this.state.tableData )
// Set newArtists as this.state.newArtists
.then( newArtists => this.setNewArtistsState( newArtists )
// Merge the current & new
.then( newArtists => mergeArtists(this.state.currentArtists, newArtists)
// Set mergedArtists as this.state.mergedArtists
.then( mergedArtists => this.setMergedArtistsState( mergedArtists )
// Now create the new artists and return updated array
.then( createArtists(this.state.mergedArtists) )
// Log the resolve of createArtists
.then( (updatedArtists) => {
// THIS SHOULD BE THE SAME AS THE RESOLVE IN artists.js
console.log('then updatedArtists', updatedArtists);
})
)
)
)
)
);
}
@NRDay
Copy link
Author

NRDay commented Sep 3, 2020

Here is the console output

Screenshot 2020-09-03 at 10 18 53

I had thought that by using a promise inside the forEach loop, it would wait for each promise to resolve before resolving the promise inside createArtists, but clearly not.

I've also tried it using map(), a basic for loop, using a counter and only resolving when the count === updatedArtists.length, but no joy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment