https://bigfrontend.dev/zh/problem/implement-Promise-allSettled

    1. /**
    2. * @param {Array<any>} promises - notice that input might contains non-promises
    3. * @return {Promise<Array<{status: 'fulfilled', value: any} | {status: 'rejected', reason: any}>>}
    4. */
    5. function allSettled(promises) {
    6. // your code here
    7. const n = promises.length;
    8. let ans = [];
    9. let count = 0;
    10. return new Promise((resolve) => {
    11. if (n == 0) resolve([]);
    12. for (let i = 0; i < n; i++) {
    13. Promise.resolve(promises[i])
    14. .then((value) => {
    15. ans[i] = {
    16. status: 'fulfilled',
    17. value,
    18. };
    19. if (++count == n) resolve(ans);
    20. })
    21. .catch((reason) => {
    22. ans[i] = {
    23. status: 'rejected',
    24. reason,
    25. };
    26. if (++count == n) resolve(ans);
    27. })
    28. }
    29. })
    30. }