【代码鉴赏】简单优雅的JavaScript代码片断

首个成功的Promise

从一组Promise里面获得第一个“成功的”结果,同时得到了并发执行的速度和容灾的能力。api

Promise.race不知足需求,由于若是有一个Promise reject,结果Promise也会当即reject;
Promise.all也不知足需求,由于它会 等待全部Promise,而且要求全部Promise都成功resolve。
function firstSuccess(promises){
  return Promise.all(promises.map(p => {
    // If a request fails, count that as a resolution so it will keep
    // waiting for other possible successes. If a request succeeds,
    // treat it as a rejection so Promise.all immediately bails out.
    return p.then(
      val => Promise.reject(val),
      err => Promise.resolve(err)
    );
  })).then(
    // If '.all' resolved, we've just got an array of errors.
    errors => Promise.reject(errors),
    // If '.all' rejected, we've got the result we wanted.
    val => Promise.resolve(val)
  );
}

把resolve的Promise反转成reject,把reject的Promise反转成resolve,而后用Promise.all合并起来。
这样的话,只要有一个原始Promise成功resolve,就会形成Promise.all马上被reject,实现提早退出!太巧妙了!数组

这个方法适合的场景:promise

  • 有多条路能够走,其中任意一条路走通便可,其中有一些路失败也不要紧
  • 为了加速获得结果,并发地走多条路,避免瀑布式尝试

参考自 https://stackoverflow.com/a/3...并发

异步reduce

有时候业务逻辑要求咱们必须串行地处理多个数据,不能像上面那样并发地处理多个数据。即,经过瀑布式的异步操做,将一个数组reduce成一个值。这个时候能够巧妙地使用array.reduce:异步

(async () => {
    const data = [1, 2, 3]
    const result = await data.reduce(async (accumP, current, index) => {
      // 后面的处理要等待前面完成
      const accum = await accumP;
      const next = await apiCall(accum, current);
      return next
    }, 0);
    console.log(result)  // 6

    async function apiCall(a, b) {
        return new Promise((res)=> {
            setTimeout(()=> {res(a+b);}, 300)
        })
    }
})()

与更常见的【array.map + Promise.all方案】对比:async

(async () => {
  const data = [1, 2, 3]
  const result = await Promise.all(
    data.map(async (current, index) => {
      // 处理是并发的
      return apiCall(current)
    })
  )
  console.log(result)

  async function apiCall(a) {
    return new Promise((res) => {
      setTimeout(() => {
        res(a * 2)
      }, 300)
    })
  }
})()
  • 两个方案相同点:对每一个数组项执行处理,而且其中任一次处理的失败都会形成总体失败
  • reduce方案是瀑布式的,map方案是并发的
  • reduce方案,当你处理到第n项的时候,你可使用以前的累积量

参考自 https://stackoverflow.com/a/4...code

相关文章
相关标签/搜索