數組的遍歷你都會用了,那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

相關文章
相關標籤/搜索