代码鉴赏简单优雅的JavaScript代码片段

10次阅读

共计 1365 个字符,预计需要花费 4 分钟才能阅读完成。

首个成功的 Promise

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

Promise.race 不满足需求,因为如果有一个 Promise reject,结果 Promise 也会立即 reject。

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)
  );
}

这个方法适合的场景:

  • 有多条路可以走,其中任意一条路走通即可,其中有一些路失败也没关系
  • 为了加速得到结果,并发地走多条路,避免瀑布式 尝试

参考自 https://stackoverflow.com/a/3…

异步 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)
        })
    }
})()

对 reduce 的运用堪称巧妙!

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

(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 方案是并发的

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

正文完
 0