At this moment, your promises are executing serially. Is this by design? If you prefer them to run in parallel, you can easily check the status of each using Promise.allSettled
.
If you want them to execute sequentially, you could loop through all the conditions and stop if any fails, returning a failure status for the remaining promises. If all conditions pass, it will return an empty object.
const conditions = [firstCondition, secondCondition, thirdCondition];
const result = await conditions.reduce(async (status, condition, index) => {
// Skip running current condition if we've already failed
// Return failure status instead
if(status.failed) {
return status;
}
// Run the condition
const test = await condition();
// Return accumulator if successful, set status as failed if not
return test ? status : { failed: true, failedAt: index }
}, {});
if(result.failed) {
console.log('Condition failed: ', conditions[result.failedAt]);
}
You can simplify the code above like this:
const conditions = [firstCondition, secondCondition, thirdCondition];
const result = await conditions.reduce(async (status, condition, index) =>
status.failed ?
status :
await condition() ?
status :
{ failed: index },
{}
);
if('failed' in result) {
console.log('Condition failed: ', conditions[result.failed]);
}
Next, organize it into a utility function:
const promiseAnd = async (...conditions) => await conditions.reduce(async (status, condition, index) =>
status.failed ?
status :
await condition() ?
status :
{ failed: index },
{}
);
const { failed } = await promiseAnd(firstCondition, secondCondition, thirdCondition);
if(failed) {
console.log(`Promise ${failed} failed`);
}