请参阅下面的代码
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]
快速编辑: 公认的答案是正确的,说地图没有对异步函数做任何特别的事情。我不知道为什么我认为它识别出异步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
函数总是返回承诺;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
函数总是返回承诺,而您在功能中唯一的await
是您创建的承诺,因此无论如何在这里使用async
功能是没有意义的。只需返回您要创建的承诺:
var arr = [1,2,3,4,5].map((index) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(index);
console.log(index);
}, 1000);
});
});
当然,如果您确实在其中做一些更有趣的事情,而await
s在各种方面(而不是在new Promise(...)
上),那就是不同的。: - )
由于它是异步,因此在 map
返回时尚未确定值。在运行箭头功能之前,它们将不存在。
这就是为什么存在承诺的原因。它们是将来有价值的承诺。