[英]Why does async array map return promises, instead of values
見下面的代碼
var arr = await [1,2,3,4,5].map(async (index) => {
return await new Promise((resolve, reject) => {
setTimeout(() => {
resolve(index);
console.log(index);
}, 1000);
});
});
console.log(arr); // <-- [Promise, Promise, Promise ....]
// i would expect it to return [1,2,3,4,5]
快速編輯:通過說map對異步功能沒有做任何特殊的事情,可接受的答案是正確的。 我不知道為什么我認為它可以識別異步fn並知道等待響應。
也許我期待這樣的事情。
Array.prototype.mapAsync = async function(callback) {
arr = [];
for (var i = 0; i < this.length; i++)
arr.push(await callback(this[i], i, this));
return arr;
};
var arr = await [1,2,3,4,5].mapAsync(async (index) => {
return await new Promise((resolve, reject) => {
setTimeout(() => {
resolve(index);
console.log(index);
}, 1000);
});
});
// outputs 1, 2 ,3 ... with 1 second intervals,
// arr is [1,2,3,4,5] after 5 seconds.
因為async
函數總是返回promise; map
沒有異步性的概念,也沒有對諾言的特殊處理。
但是您可以隨時通過Promise.all
等待結果:
try {
const results = await Promise.all(arr);
// Use `results`, which will be an array
} catch (e) {
// Handle error
}
現場示例:
var arr = [1,2,3,4,5].map(async (index) => { return await new Promise((resolve, reject) => { setTimeout(() => { resolve(index); console.log(index); }, 1000); }); }); (async() => { try { console.log(await Promise.all(arr)); // Use `results`, which will be an array } catch (e) { // Handle error } })();
.as-console-wrapper { max-height: 100% !important; }
或使用Promise語法
Promise.all(arr)
.then(results => {
// Use `results`, which will be an array
})
.catch(err => {
// Handle error
});
現場示例:
var arr = [1,2,3,4,5].map(async (index) => { return await new Promise((resolve, reject) => { setTimeout(() => { resolve(index); console.log(index); }, 1000); }); }); Promise.all(arr) .then(results => { console.log(results); }) .catch(err => { // Handle error });
.as-console-wrapper { max-height: 100% !important; }
旁注:由於async
函數總是返回promise,而函數中await
的唯一事情就是您創建的promise,因此無論如何在這里使用async
函數都沒有意義。 只需返回您正在創建的承諾即可:
var arr = [1,2,3,4,5].map((index) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(index);
console.log(index);
}, 1000);
});
});
當然,如果您確實在其中做一些更有趣的事情,並且在各種事情上都進行了await
(而不僅僅是在new Promise(...)
),那就不一樣了。 :-)
由於它是異步的,因此尚未在返回map
確定值。 在運行箭頭功能之前,它們將不存在。
這就是承諾存在的原因。 它們是未來價值的保證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.