這裡指的遍歷方法包括:map、reduce、reduceRight、forEach、filter、some、every因為最近要進行了一些數據彙總,node版本已經是8.11.1了,所以直接寫了個async/await的腳本。但是在對數組進行一些遍歷操作時,發現有些遍歷方法對Promise的反饋並不 ...
這裡指的遍歷方法包括:
map
、reduce
、reduceRight
、forEach
、filter
、some
、every
因為最近要進行了一些數據彙總,node
版本已經是8.11.1了,所以直接寫了個async/await
的腳本。
但是在對數組進行一些遍歷操作時,發現有些遍歷方法對Promise
的反饋並不是我們想要的結果。
當然,有些嚴格來講並不能算是遍歷,比如說some
,every
這些的。
但確實,這些都會根據我們數組的元素來進行多次的調用傳入的回調。
這些方法都是比較常見的,但是當你的回調函數是一個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
接收兩個參數:
- 對每項元素執行的回調,回調結果的返回值將作為該數組中相應下標的元素
- 一個可選的回調函數
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
的函數簽名想必大家也很熟悉了,接收兩個參數:
- 對每一項元素執行的回調函數,返回值將被累加到下次函數調用中,回調函數的簽名:
accumulator
累加的值currentValue
當前正在處理的元素currentIndex
當前正在處理的元素下標array
調用reduce
的數組
- 可選的初始化的值,將作為
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
,這個應該是用得最多的遍歷方法了,對應的函數簽名:
callback
,對每一個元素進行調用的函數currentValue
,當前元素index
,當前元素下標array
,調用forEach
的數組引用
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 0
、await 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 // > false
當匹配到任意一個false
時,直接返回false
,終止遍歷。
後記
關於數組的這幾個遍歷方法。
因為map
和reduce
的特性,所以是在使用async
時改動最小的函數。reduce
的結果很像一個洋蔥模型
但對於其他的遍歷函數來說,目前來看就需要自己來實現了。
四個*Sync
函數的實現:https://github.com/Jiasm/notebook/tree/master/array-sync