Trace the fixed program
Three local promises represent Markup, a Local failure and Layout. Inspect all three outcomes rather than treating the rejected one as successful.
const jobs=[Promise.resolve('Markup'),Promise.reject('Local failure'),Promise.resolve('Layout')];
Promise.allSettled(jobs).then(results=>console.log(JSON.stringify(results)));
[{"status":"fulfilled","value":"Markup"},{"status":"rejected","reason":"Local failure"},{"status":"fulfilled","value":"Layout"}]| Input job | Status | Stored field |
|---|---|---|
| Markup | fulfilled | value: Markup |
| Local failure | rejected | reason: Local failure |
| Layout | fulfilled | value: Layout |
Explain the result
allSettled fulfills with one settlement record per input once all settle. Fulfilled records have value; rejected records have reason. Result positions follow the input iterable, even if settlement order differs. A never-settling input would keep the combined result pending; none is supplied here.
Test the alternative
Promise.all rejects for these inputs instead of providing the per-input settlement array. Its catch handles the failure in this separate example.
const jobs=[Promise.resolve('Markup'),Promise.reject('Local failure'),Promise.resolve('Layout')];
Promise.all(jobs).then(values=>console.log(JSON.stringify(values))).catch(reason=>console.log(JSON.stringify({reason})));
{"reason":"Local failure"}Work the boundary case
If the second deferred promise is resolved first, where does it appear in the result?
Show the worked answer
No. It remains second. The following fixed example settles Second before First but returns First, Second.
let first,second;const jobs=[new Promise(resolve=>{first=resolve;}),new Promise(resolve=>{second=resolve;})];
const settlementOrder=[];const result=Promise.allSettled(jobs);second('Second');settlementOrder.push('Second');first('First');settlementOrder.push('First');
result.then(results=>console.log(JSON.stringify({settlementOrder,results})));
{"settlementOrder":["Second","First"],"results":[{"status":"fulfilled","value":"First"},{"status":"fulfilled","value":"Second"}]}