0
点赞
收藏
分享

微信扫一扫

JS手写一个promise方法

金刚豆 2022-04-14 阅读 112

 源代码:

// 实现一个promise.all()
function promiseAll(array) {
    return new Promise((resolve, reject) => {
        if (!(array instanceof Array)) {
            reject(new Error("params is not a valid array"));
        }
        let resultArr = new Array(array.length),
            count = 0;
        for (let i = 0; i < array.length; i++) {
            Promise.resolve(array[i])
                .then((res) => {
                    count++;
                    resultArr[i] = res;
                    if (count === array.length) resolve(resultArr);
                })
                .catch((error) => reject(error));
        }
    });
}

// 定义一个promise的生成器

const promiseGenerator = (num) =>
    new Array(num).fill(0).map(
        (_, index) =>
            //如果没有用到item可以写成_
            new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(index);
                }, Math.random() * 1000);
            })
    );

const proAll = promiseGenerator(10);
promiseAll(proAll).then(console.log);

案例结果图:

 知识点扩展:

 

举报

相关推荐

0 条评论