手写Promise.all/allSettled

70 阅读1分钟

Promise.all

function PromiseAll(arr) {
    if (!Array.isArray(promiseArray)) { 
        return reject(new Error('传入的参数不是数组!')) 
    }

    const resArr = [];
    let counter = 0;
    return new Promise((resolve, reject) => {
        for (let index = 0; index < arr.length; index++) {
            Promise.resolve(arr[index]).then((res) => {
                resArr[index] = res;
                counter++;
                if (counter === arr.length) {
                    resolve(resArr);
                }
            }).catch((e) => {
                reject(e);
            })
        }
    })
}

Promise.allSettled

function PromiseAllSettled(arr) {
    if (!Array.isArray(promiseArray)) { 
        return reject(new Error('传入的参数不是数组!')) 
    }

    const resArr = [];
    let counter = 0;
    return new Promise((resolve, reject) => {
        for (let index = 0; index < arr.length; index++) {
            Promise.resolve(arr[index]).then((res) => {
                resArr[index] = { status: 'fulfilled', value: res };
            }).catch((e) => {
                resArr[index] = { status: 'rejected', reason: e };
            }).finally(() => {
                counter++;
                if (counter === arr.length) {
                    resolve(resArr);
                }
            })
        }
    })
}