ZhangCheng-zh / blog

记录一些code
0 stars 0 forks source link

Custom Promise all and race #10

Open ZhangCheng-zh opened 2 years ago

ZhangCheng-zh commented 2 years ago

Promise all

Key point:

function promiseAll (promisesList) {
    return new Promise((resolve, reject) => {
        const promisesResult = []
        let count = 0
        const len = promisesList.length
        for (let i = 0; i < len; i++) {
            Promise.resolve(promisesList[i]).then(res => {
                promisesResult[i] = res
                if (++count === len) {
                    resolve(promisesResult)
                }
            }).catch(e => {
                reject(e)
            })
        }
        if (promisesList.length === 0) {
            return resolve([])
        }
    })
}