其他分享
首页 > 其他分享> > 手写promise.all和 promise.race

手写promise.all和 promise.race

作者:互联网

// promise.all
function promiseAll(promisesArr) {
    return new Promise((resolve, reject) => {
        // 定义一个计数器
        let count = 0;
        const arr = [];
        const l = promisesArr.length;
        let startTime = new Date().getTime();
        for (let i = 0; i < l; i++) {
            promisesArr[i]
                .then((res) => {
                    count++;
                    // arr.push(res); 这里不能直接 push ,因为要保证 顺序
                    arr[i] = res;
                    if (count === l) {
                        resolve(arr);
                        let endTime = new Date().getTime();
                        console.log(endTime - startTime); // 耗费的总时长为最长的 promise 时长
                    }
                })
                .catch((err) => {
                    // console.log(err);
                    reject(err);
                });
        }
    });
}

const promiseA = new Promise((resolve, reject) => {
    resolve("A");
});
const promiseB = new Promise((resolve, reject) => {
    reject("B error");
    // resolve("B");
});

promiseAll([promiseA, promiseB])
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.log(err);
    });

let wake = (time) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(`${time / 1000}秒后醒来`);
        }, time);
    });
};

let p1 = wake(3000);
let p2 = wake(2000);

Promise.all([p1, p2])
    .then((result) => {
        console.log(result); // [ '3秒后醒来', '2秒后醒来' ]  按照顺序输出
    })
    .catch((error) => {
        console.log(error);
    });

promiseAll([p1, p2])
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.log(err);
    });

// Promise.race
// Promse.race就是赛跑的意思,意思就是说,Promise.race([p1, p2, p3])里面哪个结果获得的快,就返回那个结果,不管结果本身是成功状态还是失败状态。
let p11 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("success");
    }, 1000);
});

let p22 = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject("failed");
    }, 500);
});

Promise.race([p11, p22])
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.log(error); //'failed'
    });

function promiseRace(promiseArr) {
    return new Promise((resolve, reject) => {
        for (let i = 0; i < promiseArr.length; i++) {
            promiseArr[i]
                .then((res) => {
                    resolve(res);
                })
                .catch((err) => {
                    reject(err);
                });
        }
    });
}
promiseRace([p11, p22])
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.log(err);
    });//'failed'
学习链接:https://www.jianshu.com/p/7e60fc1be1b2

标签:resolve,console,log,err,res,race,promise,Promise,手写
来源: https://www.cnblogs.com/beileixinqing/p/16597282.html