数组的遍历你都会用了,那Promise版本的呢

这里指的遍历方法包括: mapreducereduceRightforEachfiltersomeevery
由于最近要进行了一些数据汇总, node版本已是8.11.1了,因此直接写了个 async/await的脚本。
可是在对数组进行一些遍历操做时,发现有些遍历方法对 Promise的反馈并非咱们想要的结果。

固然,有些严格来说并不能算是遍历,好比说someevery这些的。
但确实,这些都会根据咱们数组的元素来进行屡次的调用传入的回调。javascript

这些方法都是比较常见的,可是当你的回调函数是一个Promise时,一切都变了。java

前言

async/awaitPromise的语法糖
文中会直接使用async/await替换Promisenode

let result = await func()
// => 等价于
func().then(result => {
  // code here
})

// ======

async function func () {
  return 1  
}
// => 等价与
function func () {
  return new Promise(resolve => resolve(1))
}

map

map能够说是对Promise最友好的一个函数了。
咱们都知道,map接收两个参数:git

  1. 对每项元素执行的回调,回调结果的返回值将做为该数组中相应下标的元素
  2. 一个可选的回调函数this指向的参数
[1, 2, 3].map(item => item ** 2) // 对数组元素进行求平方
// > [1, 4, 9]

上边是一个普通的map执行,可是当咱们的一些计算操做变为异步的:github

[1, 2, 3].map(async item => item ** 2) // 对数组元素进行求平方
// > [Promise, Promise, Promise]

这时候,咱们获取到的返回值其实就是一个由Promise函数组成的数组了。数组

因此为何上边说map函数为最友好的,由于咱们知道,Promise有一个函数为Promise.all
会将一个由Promise组成的数组依次执行,并返回一个Promise对象,该对象的结果为数组产生的结果集。异步

await Promise.all([1, 2, 3].map(async item => item ** 2))
// > [1, 4, 9]

首先使用Promise.all对数组进行包装,而后用await获取结果。async

reduce/reduceRight

reduce的函数签名想必你们也很熟悉了,接收两个参数:函数

  1. 对每一项元素执行的回调函数,返回值将被累加到下次函数调用中,回调函数的签名:性能

    1. accumulator累加的值
    2. currentValue当前正在处理的元素
    3. currentIndex当前正在处理的元素下标
    4. array调用reduce的数组
  2. 可选的初始化的值,将做为accumulator的初始值
[1, 2, 3].reduce((accumulator, item) => accumulator + item, 0) // 进行加和
// > 6

这个代码也是没毛病的,一样若是咱们加和的操做也是个异步的:

[1, 2, 3].reduce(async (accumulator, item) => accumulator + item, 0) // 进行加和
// > Promise {<resolved>: "[object Promise]3"}

这个结果返回的就会很诡异了,咱们在回看上边的reduce的函数签名

对每一项元素执行的回调函数,返回值将被累加到下次函数调用中

而后咱们再来看代码,async (accumulator, item) => accumulator += item
这个在最开始也提到了,是Pormise的语法糖,为了看得更清晰,咱们能够这样写:

(accumulator, item) => new Promise(resolve =>
  resolve(accumulator += item)
)

也就是说,咱们reduce的回调函数返回值其实就是一个Promise对象
而后咱们对Promise对象进行+=操做,获得那样怪异的返回值也就很合情合理了。

固然,reduce的调整也是很轻松的:

await [1, 2, 3].reduce(async (accumulator, item) => await accumulator + item, 0)
// > 6

咱们对accumulator调用await,而后再与当前item进行加和,在最后咱们的reduce返回值也必定是一个Promise,因此咱们在最外边也添加await的字样
也就是说咱们每次reduce都会返回一个新的Promise对象,在对象内部都会获取上次Promise的结果。
咱们调用reduce实际上获得的是相似这样的一个Promise对象:

new Promise(resolve => {
  let item = 3
  new Promise(resolve => {
      let item = 2
      new Promise(resolve => {
        let item = 1
        Promise.resolve(0).then(result => resolve(item + result))
      }).then(result => resolve(item + result))
  }).then(result => resolve(item + result))
})

reduceRight

这个就没什么好说的了。。跟reduce只是执行顺序相反而已

forEach

forEach,这个应该是用得最多的遍历方法了,对应的函数签名:

  1. callback,对每个元素进行调用的函数

    1. currentValue,当前元素
    2. index,当前元素下标
    3. array,调用forEach的数组引用
  2. thisArg,一个可选的回调函数this指向

咱们有以下的操做:

// 获取数组元素求平方后的值
[1, 2, 3].forEach(item => {
  console.log(item ** 2)
})
// > 1
// > 4
// > 9

普通版本咱们是能够直接这么输出的,可是若是遇到了Promise

// 获取数组元素求平方后的值
[1, 2, 3].forEach(async item => {
  console.log(item ** 2)
})
// > nothing

forEach并不关心回调函数的返回值,因此forEach只是执行了三个会返回Promise的函数
因此若是咱们想要获得想要的效果,只可以本身进行加强对象属性了:

Array.prototype.forEachSync = async function (callback, thisArg) {
  for (let [index, item] of Object.entries(this)) {
    await callback(item, index, this)
  }
}

await [1, 2, 3].forEachSync(async item => {
  console.log(item ** 2)
})

// > 1
// > 4
// > 9

await会忽略非Promise值,await 0await undefined与普通代码无异

filter

filter做为一个筛选数组用的函数,一样具备遍历的功能:
函数签名同forEach,可是callback返回值为true的元素将被放到filter函数返回值中去。

咱们要进行一个奇数的筛选,因此咱们这么写:

[1, 2, 3].filter(item => item % 2 !== 0)
// > [1, 3]

而后咱们改成Promise版本:

[1, 2, 3].filter(async item => item % 2 !== 0)
// > [1, 2, 3]

这会致使咱们的筛选功能失效,由于filter的返回值匹配不是彻底相等的匹配,只要是返回值能转换为true,就会被认定为经过筛选。
Promise对象必然是true的,因此筛选失效。
因此咱们的处理方式与上边的forEach相似,一样须要本身进行对象加强
但咱们这里直接选择一个取巧的方式:

Array.prototype.filterSync = async function (callback, thisArg) {
  let filterResult = await Promise.all(this.map(callback))
  // > [true, false, true]

  return this.filter((_, index) => filterResult[index])
}

await [1, 2, 3].filterSync(item => item % 2 !== 0)

咱们能够直接在内部调用map方法,由于咱们知道map会将全部的返回值返回为一个新的数组。
这也就意味着,咱们map能够拿到咱们对全部item进行筛选的结果,true或者false
接下来对原数组每一项进行返回对应下标的结果便可。

some

some做为一个用来检测数组是否知足一些条件的函数存在,一样是能够用做遍历的
函数签名同forEach,有区别的是当任一callback返回值匹配为true则会直接返回true,若是全部的callback匹配均为false,则返回false

咱们要判断数组中是否有元素等于2

[1, 2, 3].some(item => item === 2)
// > true

而后咱们将它改成Promise

[1, 2, 3].some(async item => item === 2)
// > true

这个函数依然会返回true,可是却不是咱们想要的,由于这个是async返回的Promise对象被认定为true

因此,咱们要进行以下处理:

Array.prototype.someSync = async function (callback, thisArg) {
  for (let [index, item] of Object.entries(this)) {
    if (await callback(item, index, this)) return true
  }

  return false
}
await [1, 2, 3].someSync(async item => item === 2)
// > true

由于some在匹配到第一个true以后就会终止遍历,因此咱们在这里边使用forEach的话是在性能上的一种浪费。
一样是利用了await会忽略普通表达式的优点,在内部使用for-of来实现咱们的需求

every

以及咱们最后的一个every
函数签名一样与forEach同样,
可是callback的处理仍是有一些区别的:
其实换一种角度考虑,every就是一个反向的some
some会在获取到第一个true时终止
every会在获取到第一个false时终止,若是全部元素均为true,则返回true

咱们要断定数组中元素是否所有大于3

[1, 2, 3].every(item => item > 3)
// > false

很显然,一个都没有匹配到的,并且回调函数在执行到第一次时就已经终止了,不会继续执行下去。
咱们改成Promise版本:

[1, 2, 3].every(async => item > 3)
// > true

这个必然是true,由于咱们判断的是Promise对象
因此咱们拿上边的someSync实现稍微修改一下:

Array.prototype.everySync = async function (callback, thisArg) {
  for (let [index, item] of Object.entries(this)) {
    if (!await callback(item, index, this)) return false
  }

  return true
}
await [1, 2, 3].everySync(async item => item === 2)
// > false

当匹配到任意一个false时,直接返回false,终止遍历。

后记

关于数组的这几个遍历方法。
由于mapreduce的特性,因此是在使用async时改动最小的函数。
reduce的结果很像一个洋葱模型
但对于其余的遍历函数来讲,目前来看就须要本身来实现了。

四个*Sync函数的实现:https://github.com/Jiasm/notebook/tree/master/array-sync

参考资料

Array - JavaScript | MDN

相关文章
相关标签/搜索