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

匿名 (未验证) 提交于 2019-12-02 21:53:52

这里指的遍历方法包括:mapreducereduceRightforEachfiltersomeevery
因为最近要进行了一些数据汇总,node版本已经是8.11.1了,所以直接写了个async/await的脚本。
但是在对数组进行一些遍历操作时,发现有些遍历方法对Promise的反馈并不是我们想要的结果。

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

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

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

 1 let result = await func()  2 // => 等价于  3 func().then(result => {  4   // code here  5 })  6   7 // ======  8   9 async function func () { 10   return 1   11 } 12 // => 等价与 13 function func () { 14   return new Promise(resolve => resolve(1)) 15 }

map

map可以说是对Promise最友好的一个函数了。
我们都知道,map接收两个参数:

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

上边是一个普通的map执行,但是当我们的一些计算操作变为异步的:

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

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

所以为什么上边说map函数为最友好的,因为我们知道,Promise有一个函数为Promise.all
会将一个由Promise组成的数组依次执行,并返回一个Promise对象,该对象的结果为数组产生的结果集。

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

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

reduce/reduceRight

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

  1. 对每一项元素执行的回调函数,返回值将被累加到下次函数调用中,回调函数的签名:
    1. accumulator累加的值
    2. currentValue当前正在的元素
    3. array调用reduce的数组
  2. 可选的初始化的值,将作为accumulator的初始值
1 [1, 2, 3].reduce((accumulator, item) => accumulator + item, 0) // 进行加和 2 // > 6

这个代码也是没毛病的,同样如果我们加和的操作也是个异步的:

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

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

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

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

1 (accumulator, item) => new Promise(resolve => 2   resolve(accumulator += item) 3 )

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

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

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

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

 1 new Promise(resolve => {  2   let item = 3  3   new Promise(resolve => {  4       let item = 2  5       new Promise(resolve => {  6         let item = 1  7         Promise.resolve(0).then(result => resolve(item + result))  8       }).then(result => resolve(item + result))  9   }).then(result => resolve(item + result)) 10 })

reduceRight

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

forEach

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

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

我们有如下的操作:

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

普通版本我们是可以直接这么输出的,但是如果遇到了Promise

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

forEach并不关心回调函数的返回值,所以forEach只是执行了三个会返回Promise的函数
所以如果我们想要得到想要的效果,只能够自己进行增强对象属性了:

 1 Array.prototype.forEachSync = async function (callback, thisArg) {  2   for (let [index, item] of Object.entries(this)) {  3     await callback(item, index, this)  4   }  5 }  6   7 await [1, 2, 3].forEachSync(async item => {  8   console.log(item ** 2)  9 }) 10  11 // > 1 12 // > 4 13 // > 9

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

filter

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

我们要进行一个奇数的筛选,所以我们这么写:

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

然后我们改为Promise版本:

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

这会导致我们的筛选功能失效,因为filter的返回值匹配不是完全相等的匹配,只要是返回值能转换为true,就会被认定为通过筛选。
Promise对象必然是true的,所以筛选失效。
所以我们的处理方式与上边的forEach类似,同样需要自己进行对象增强
但我们这里直接选择一个取巧的方式:

1 Array.prototype.filterSync = async function (callback, thisArg) { 2   let filterResult = await Promise.all(this.map(callback)) 3   // > [true, false, true] 4  5   return this.filter((_, index) => filterResult[index]) 6 } 7  8 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 [1, 2, 3].some(item => item === 2) 2 // > true

然后我们将它改为Promise

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

这个函数依然会返回true,但是却不是我们想要的,因为这个是async返回的Promise对象被认定为true

所以,我们要进行如下处理:

1 Array.prototype.someSync = async function (callback, thisArg) { 2   for (let [index, item] of Object.entries(this)) { 3     if (await callback(item, index, this)) return true 4   } 5  6   return false 7 } 8 await [1, 2, 3].someSync(async item => item === 2) 9 // > true

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

every

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

我们要判定数组中元素是否全部大于3

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

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

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

这个必然是true,因为我们判断的是Promise对象
所以我们拿上边的someSync实现稍微修改一下:

1 Array.prototype.everySync = async function (callback, thisArg) { 2   for (let [index, item] of Object.entries(this)) { 3     if (!await callback(item, index, this)) return false 4   } 5  6   return true 7 } 8 await [1, 2, 3].everySync(async item => item === 2) 9 // > true

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

关于数组的这几个遍历方法。
因为mapreduce的特性,所以是在使用async时改动最小的函数。
reduce的结果很像一个洋葱模型
但对于其他的遍历函数来说,目前来看就需要自己来实现了。

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

Array - JavaScript | MDN

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!