【发布时间】:2017-11-29 16:10:13
【问题描述】:
请看下面的代码
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.
【问题讨论】:
-
当您清楚地为每个值返回新的
Promise时,为什么会期望有任何不同
标签: javascript promise async-await