乐趣区

关于javascript:手写promise的all与race

实现 promise 的 all 与 race

Promise.all(iterable)

总结:
Promise 承受一个 iterable 类型的输出(如 Array、Set、Map)等,
当 iterable 参数所有的 Promise 对象都 resolve 时,该办法会返回一个蕴含所有 resolve 传递的值的 Promise 实例。

办法实例

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {console.log(values);
});
// expected output: Array [3, 42, "foo"]

手写实现

function promiseAll(arrays){if(!Array.isArray(arrays))
    return 'not Array'
    var promiseValues = []
    var promiseCount = 0
    return new Promise((resolve,reject)=>{for(var i = 0; i < arrays.length; i++){Promise.resolve(arrays[i]).then((value)=>{promiseValues.push(value)
             promiseCount++
             if(promiseCount == arrays.length)
                resolve(promiseValues)
        }, (err)=>{reject(err)})
    }
  })
}

测试用例

promiseAll([promise1,promise2,promise3]).then((values)=>{console.log(values)})
//[3, 42, "foo"]

Promise.race(iterable)

总结:当 iterable 参数中任意一个 promise 胜利或失败,则返回蕴含该值的 promise 实例。

办法实例

const promise1 = new Promise((resolve, reject) => {setTimeout(resolve, 500, 'one');
});

const promise2 = new Promise((resolve, reject) => {setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then((value) => {console.log(value);
  // Both resolve, but promise2 is faster
});
// expected output: "two"

手写实现

function promiseRace(arrays){if(!Array.isArray(arrays))
    return 'not Array'
    return new Promise((resolve,reject)=>{for(var i = 0; i < arrays.length; i++){Promise.resolve(arrays[i]).then((value)=>{resolve(value)
        }, (err)=>{reject(err)})
    }
  })
}

测试用例

promiseRace([promise1,promise2]).then(function(value){console.log(value)})  // one
退出移动版