手写promise的all方法以及finally方法

点击查看代码
// 实现promise.all
// Promise.all = function(){
// }

Promise.all = (arr) => {
    return new Promise((resolve,reject) => {
        let res = [];
        let count = 0;
        for(let i = 0; i < arr.length; i++){
            // 强制转化为promise
            Promise.resolve(arr[i])
            .then((value) => {
                res[i] = value;
                count++;

                if(count === arr.length){
                    resolve(res)
                }
            })
            .catch((reason) => {
                reject(reason)
            })
        }
    });
}


Promise.prototype.finally = function(callback){
    return this.then(
        (value) => {
            return Promise.resolve(callback()).then(() => value);
        },
        (err) => {
            return Promise.resolve(callback()).then(() => {throw err});
        }
    )
}
posted on 2022-02-08 17:38  Liillian  阅读(302)  评论(0编辑  收藏  举报