Async 版本的数组,用起来可方便了 ~ 😏😏
发布于 4 年前 作者 Bin-Huang 4177 次浏览 来自 分享

JS 原本的数组对异步调用太不友好了,比如不能这么做 const result = await arr.map(func),必须要在外面再套一层 await Promise.all(...),实在不够简洁、直观、优雅。不过如果用这个包 Prray 代替数组的话,,就可以做到上面的效果了

import Prray from 'prray'
const prr = Prray.from(['www.google.com', 'npmjs.org'])

console.log(prr[0])    // www.google.com
console.log(prr.length)  // 2

const responses = await prr.mapAsync(fetch)

// 异步函数也能链状调用
const htmls = await prr.mapAsync(fetch).mapAsync(r => r.text())

// 普通函数和异步函数也能链状调用
await prr
  .map(commonFunc)
  .sortAsync(asyncFunc)
  .concat(['github.com', 'wikipedia.org'])
  .reverse()
  .splice(1, 2)
  .reduceAsync(asyncFunc2)

// 限制并发
const responses = await prr.mapAsync(fetch, { concurrency: 10 })
  • 黑科技 异步方法也能链状调用
  • 和原来的数组完美兼容arr[ix] 索引、...arr 展开、for of 循环……原来数组所有能做的都能做,可以直接用来替代数组。
  • 测试非常良好,不管是兼容性还是新方法,这个包的测试都非常充分: 不信你看
  • 性能优异(基于 native Promise)。如果不异步调用,方法们的性能和原生 Array 没有差别;如果异步调用,性能也就是手动使用 Promise 一样。
  • 非常轻量,没有其他三方依赖,打包后更小

github: https://github.com/Bin-Huang/prray

1 回复

感觉可以 围观一下

回到顶部