Javascript

js 手写promise.all

本文主要是介绍js 手写promise.all,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
  1. 入参必须实现iterator接口,一般为数组
  2. 全部成功才算成功,有一个失败就失败, 如果成功,结果顺序和入参顺序保持一致
  3. 返回一个新的promise,
    Promise._all = function (promises) {
        if (!promises instanceof Array) throw 'promises must be an array'
        const length = promises.length
        let count = 0
        const ret = []
        if (!length) return []
        return new Promise((resolve,reject) => {
            for (let i = 0; i < promises.length; i++) {
                promises[i].then(v => {
                    count++
                    ret[i] = v
                    count === length && resolve(ret)
                }, r => {
                    reject(r)
                })
            }
        })
    }

    const doAsyncTask = (fn, timeout) => setTimeout(() => fn(), timeout)
    const p1 = new Promise((resolve, reject) => doAsyncTask(()=>{reject(1)},2000))
    const p2 = new Promise((resolve, reject) => doAsyncTask(()=>{resolve(2)},1000))
    const p3 = new Promise((resolve, reject) => doAsyncTask(()=>{resolve(3)},3000))
    const res = Promise._all([p1,p2,p3])
    res.then(v=>console.log(v),r=>console.log(r))
    console.log(res);
这篇关于js 手写promise.all的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!