Promise

1.Promise.all

// 实现Promise.all
Promise.all = function(promises){
     return new Promise((resolve,reject) => {
         if(promises.length === 0){
              resolve([])
         }else{
              let result = [], index = 0
              promises.forEach((v,i) => {
                    Promise.resolve(v).then(data => {
                        result[i] = data
                        if(++index === promises.length){
                             resolve(result)
                        }
                    }).catch(err => {
                         reject(err)
                         return
                    })
               })
         }
    }) 
}
function fun(val){
    return new Promise((resolve,reject) => {
         if(val === 3){
            reject('error...')
         }
         setTimeout(() => {
            resolve(val+'-woshifanhui')
         },2000)
    })
}
const arr = [1,2,3,4,5,6,7,8]
const promises = arr.map(v => fun(v))
Promise.all(promises).then(v => {
    console.log(v)
}).catch(e => console.log(e))

 

posted @ 2021-08-30 10:45  卷叶小树  阅读(33)  评论(0编辑  收藏  举报