请见下方代码:
快速编辑: 接受的答案是正确的,因为map对异步函数没有任何特殊处理。我不知道为什么我会认为它能识别异步函数并等待响应。
我原本期望的是这样的。
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对异步函数没有任何特殊处理。我不知道为什么我会认为它能识别异步函数并等待响应。
我原本期望的是这样的。
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
时,你为什么会期望有任何不同呢? - musefan