Right now all your promises execute serially. Is that intentional? If you want them all to execute in parallel, the easiest way to get the status of each is Promise.allSettled
.
If you want them to run in serial, you could loop over all the conditions, and if it fails, short circuit and return the failure status for the rest of them. If they all succeed, it will just return an empty object.
const conditions = [firstCondition, secondCondition, thirdCondition];
const result = await conditions.reduce(async (status, condition, index) => {
// If we've already failed, don't run the current condition,
// just return the failure status
if(status.failed) {
return status;
}
// Otherwise, run the condition..
const test = await condition();
// If it succeeded, return the accumulator, otherwise set the status
// to failed, so the next runs will short circuit
return test ? status : { failed: true, failedAt: index }
}, {});
if(result.failed) {
console.log('condition failed: ', conditions[result.failedAt]);
}
And you can shorten the above code to something like
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]);
}
and then clean it up into a utility function:
const promiseAnd = (...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`);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…