This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
33. implement `Promise.allSettled()`

Here's one possible implementation of Promise.allSettled() using Promise.all() and some additional logic:

function allSettled(promises) {
  return Promise.all(promises.map(p =>
    p.then(
      value => ({ status: "fulfilled", value }),
      reason => ({ status: "rejected", reason })
    )
  ));
}

This code takes an array of promises and maps over them, returning a new promise that resolves to an array of objects representing the fulfillment status and value or reason of each original promise.

Each promise is first transformed using then(), which formats it as an object with status and either value or reason properties, depending on whether it fulfills or rejects. The map() method then produces a new array of these transformed promises.

Finally, Promise.all() is called on this array of promises, which resolves when all of the transformed promises have either fulfilled or rejected. The resulting promises' values are an array of objects representing the original promises' fulfillment status and values or reasons.

Here's an example of using this allSettled() function:

const promises = [
  Promise.resolve(1),
  Promise.reject(new Error("Oops")),
  Promise.resolve(3)
];

allSettled(promises).then(results => {
  console.log(results);
});
// Output: [{status: "fulfilled", value: 1},
//          {status: "rejected", reason: Error: Oops},
//          {status: "fulfilled", value: 3}]

This output shows that Promise.allSettled() resolves with an array of objects describing each promise's fulfillment status and value or reason, even if some of the promises reject.