So what I am trying to do is push promises to an array of promises inside a forEach, then after the forEach I want to call Promise.all( array of promises ), however each promise is executed immediately so therefore the Promise.all is never reached.
Below is the code:
function updatePersonsPreferences( personId, preferences ) {
return new Promise( ( resolve, reject ) => {
const promises = [];
const methods = preferences.methods;
let validationError = null;
methods.forEach( ( method ) => {
// I do some validation here using a validation helper which is in another file
const functionSchema = {
person_id: { type: "integer", required: true },
type: { type: "integer", required: true },
frequency: { type: "integer", required: true },
};
const data = {
person_id: personId,
type,
frequency,
};
const validationResult = validator.isValidFunctionParameters( functionSchema, data );
if ( !validationResult.valid )
validationError = validationResult.error;
promises.push( updateMethod( personId, method.id, method.status ) ); // This is getting executed immediately when it shouldn't be
} );
// This does reject, but the promises are still run
if ( validationError ) {
return reject( validationError );
}
// EDIT: Moved console log below the rejection code above, and it is now logging [ Promise { <pending> }, Promise { <pending> } ]
console.log( promises );
// The code below never seems to be reached
return Promise.all( promises ).then( ( results ) => {
return resolve();
}, reject );
} );
}
function updateMethod( personId, methodId, status ) {
return new Promise( ( resolve, reject ) => {
// Does some database logic here
return Method.update( {
// Database logic here
} ).then( ( result ) =>
return resolve( result );
}, ( error) => {
return reject( error );
} )
} );
}