问题描述
关于javascript映射函数中async/await的行为,已经发布了很多主题,但是下面的两个示例中的详细说明还是不错的:
There is quite some topics posted about how async/await behaves in javascript map function, but still, detail explanation in bellow two examples would be nice:
const resultsPromises = myArray.map(async number => {
return await getResult(number);
});
const resultsPromises = myArray.map(number => {
return getResult(number);
});
编辑过:这当然是一个虚构的案例,因此才开始辩论,为什么,如何以及何时将map函数等待await关键字.解决方案如何修改此示例,调用Promise.all()并非此问题的目的.getResult
是一个异步函数
edited: this if of course a fictional case, so just opened for debate, why,how and when should map function wait for await keyword. solutions how to modify this example, calling Promise.all() is kind of not the aim of this question.getResult
is an async function
推荐答案
其他答案已经很好地涵盖了示例行为的详细信息,但是我想尝试更简洁地说明它.
The other answers have pretty well covered the details of how your examples behave, but I wanted to try to state it more succinctly.
const resultsPromises = myArray.map(async number => {
return await getResult(number);
});
const resultsPromises = myArray.map(number => {
return getResult(number);
});
-
Array.prototype.map
同步遍历数组,并将每个元素转换为其回调的返回值.
Array.prototype.map
synchronously loops through an array and transforms each element to the return value of its callback.
两个示例返回一个Promise
.
Both examples return a Promise
.
-
async
函数始终返回Promise
.
getResult
返回Promise
.
因此,如果没有错误,您可以在伪代码中将它们都视为:
Therefore, if there are no errors you can think of them both in pseudocode as:
const resultsPromises = myArray.map(/* map each element to a Promise */);
-
如 zero298所述和,它很快(同步)按顺序开始了每个承诺;但是,由于它们是并行运行的,每个承诺都会按照他们认为合适的方式解决/拒绝,并且可能不会按顺序解决(履行或拒绝).
As zero298 stated and alnitak demonstrated, this very quickly (synchronously) starts off each promise in order; however, since they're run in parallel each promise will resolve/reject as they see fit and will likely not settle (fulfill or reject) in order.
要么并行运行promise,然后使用Promise.all
收集结果,要么使用 for *循环依次运行它们或 Array.prototype.reduce
.
Either run the promises in parallel and collect the results with Promise.all
or run them sequentially using a for * loop or Array.prototype.reduce
.
或者,您可以将第三方模块用于可链接的异步JavaScript方法保持清理,并可能使代码符合您对异步地图操作可能会起作用:
Alternatively, you could use a third-party module for chainable asynchronous JavaScript methods I maintain to clean things up and--perhaps--make the code match your intuition of how an async map operation might work:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const getResult = async n => {
await delay(Math.random() * 1000);
console.log(n);
return n;
};
(async () => {
console.log('parallel:');
await AsyncAF([1, 2, 3]).map(getResult).then(console.log);
console.log('sequential:');
await AsyncAF([1, 2, 3]).series.map(getResult).then(console.log)
})();
<script src="https://unpkg.com/[email protected]/index.js"></script>
这篇关于具有异步/等待功能的map()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!