![](/img/trans.png)
[英]How to map items without undefined value in javascript with Array.prototype.map and without Array.prototype.filter()
[英]async / await: asynchronous array transformation using Array.prototype.map (works) vs Array.prototype.filter (not working)
我幾乎肯定要對此做一個解釋,但是我花了一個多小時試圖弄清楚為什么在嘗試使用ary.filter()
轉換數組時,我的異步代碼為什么似乎早就可以解決了,但是當使用ary.map()
異步在我期望的時候解析。 任何可以幫助闡明該主題的人將不勝感激!
為了清楚起見,我還將使用節點8.2.1。
因此,為了提供一些代碼和輸出來描述問題,這里是一個使用ary.map
的示例,該示例可以ary.map
工作並在控制台中提供以下輸出。
(async () => {
const timeStart = Date.now()
const ary = new Array(20).fill(0).map((v, i) => i+1)
const newAry = await Promise.all(
ary.map(async val => {
return await new Promise((resolve, reject) => {
setTimeout(() => resolve(val*2), 1000)
})
})
)
console.log('original ary', ary)
console.log('newAry is', newAry)
const timeEnd = Date.now()
console.log(timeEnd - timeStart, 'milliseconds between start and end')
})()
到控制台的輸出如下:
original ary [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
newAry is [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ]
1022 milliseconds between start and end
因此,正如您所期望的,轉換原始數組與輸出達到預期之間大約需要1秒鍾的時間。
以下代碼非常相似,但是使用ary.filter()
,並且未按預期返回。
(async () => {
const timeStart = Date.now()
const ary = new Array(20).fill(0).map((v, i) => i+1)
const newAry = await Promise.all(
ary.filter(async val => {
return await new Promise((resolve, reject) => {
setTimeout(() => resolve(Math.random() < 0.5), 1000)
})
})
)
console.log('original ary', ary)
console.log('newAry is', newAry)
const timeEnd = Date.now()
console.log(timeEnd - timeStart, 'milliseconds between start and end')
})()
輸出如下:
original ary [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
newAry is [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
18 milliseconds between start and end
為什么在使用async / await時在轉換數組和在適當的時間解析方面, ary.filter()
行為與ary.map()
?
調用Promise.all()
僅對一個promise數組有意義。
.map()
返回其回調的結果,如果回調是異步的,則它是一個承諾。 因此,這很好。
.filter()
將其回調結果視為布爾值(不是),然后返回原始數組中的項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.