How do I execute something after all promises within a loop have resolved?
Example code:
// ... url, headers, parameters for the requests
// Item we are iterating over and we actually use within the requests
var example = {
'Weekly',
'Monthly',
'Yearly'
};
// Set up empty results object
var results = {};
// Loop over filters and create two queries for each filter
Object.keys( example ).forEach( ( filter, index ) => {
// ... Preparing parameters depending on currently looped item
// Make first request
makeRequest( url, headers, 'GET', parameters )
.then( ( data ) => {
// ... Doing stuff with data depending on currently looped item
var firstData = data;
// Make another request with other parameters
return makeRequest( endpoint, headers, 'GET', parameters );
} )
.then( ( data ) => {
// Add both things to resultsBuild results array
results[ filter ] = {
first: firstData,
second: data
};
if ( index === Object.keys( example ).length - 1 )
exampleCallbackMethod( results ) // This should only be executed when the for loop is finished and all promises are resolved
} )
.catch( ( error ) => {
console.error( error );
} );
} );