https://bigfrontend.dev/zh/problem/implement-Promise-allSettled
/**
* @param {Array<any>} promises - notice that input might contains non-promises
* @return {Promise<Array<{status: 'fulfilled', value: any} | {status: 'rejected', reason: any}>>}
*/
function allSettled(promises) {
// your code here
const n = promises.length;
let ans = [];
let count = 0;
return new Promise((resolve) => {
if (n == 0) resolve([]);
for (let i = 0; i < n; i++) {
Promise.resolve(promises[i])
.then((value) => {
ans[i] = {
status: 'fulfilled',
value,
};
if (++count == n) resolve(ans);
})
.catch((reason) => {
ans[i] = {
status: 'rejected',
reason,
};
if (++count == n) resolve(ans);
})
}
})
}