手写promise.all

65 阅读1分钟
const list = [f, f1]
all(list).then(res => {
    console.log(res, '成功')
}).catch(err => {
    console.log(err, '失败')
})

function all(list) {
    let resultArray = []
    const count = 0
    return new Promise((resolve, reject) => {
        for (let i = 0; i < list.length; i++) {
            list[i]().then(res => {
                resultArray.push(res)
                count++
                if (count === list.length) {
                    resolve(resultArray)
                }
            }).catch(err => {
                reject(err)
            })
        }
    })
}

function f() {
    return new Promise((resolve, reject) => {
        resolve('1')
    })
}

function f1() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('2')
        }, 5000)
    })
}