[英]async await promise.all map not resolving promises
i'm trying to understand Promise.all in a map function using async await but i seem to returning promises which are pending, i don't understand why我正在尝试使用 async await 在地图函数中理解 Promise.all 但我似乎返回了未决的承诺,我不明白为什么
Here is the working code when i have a .then to resolve my promise这是我有一个 .then 来解决我的承诺时的工作代码
const arr = [1, 2, 3, 4, 5];
const results = Promise.all(arr.map( item => {
return item + 1;
}));
results.then(result=> console.log(result))
which logs as expected = [ 2, 3, 4, 5, 6 ]按预期记录 = [ 2, 3, 4, 5, 6 ]
now to implement the function using async-await i know i need to wrap the function in an async function with the keyword async and await for promise.all现在要使用 async-await 实现该功能,我知道我需要使用关键字 async 将该功能包装在一个异步函数中并等待 promise.all
const results = async () => await Promise.all(arr.map(async (item) => {
return item + 1;
}));
console.log(results())
but i always seem to log Promise { <pending> }
I don't understand what im doing wrong但我似乎总是记录
Promise { <pending> }
我不明白我做错了什么
Using asnyc
/ await
doesn't make the results
function synchronous.使用
asnyc
/ await
不会使results
函数同步。 (It's literally tagged as async
!) So it returns a promise, and you have to await
that before logging the values: (它实际上被标记为
async
!)所以它返回一个承诺,你必须在记录值之前await
它:
const arr = [1, 2, 3]; const results = Promise.all( arr.map(async item => item + 1) ); (async () => { console.log(await results) })();
What you are doing is assigning an async function to results, thats not how await for the asynchronous function works.您正在做的是将异步函数分配给结果,这不是异步函数的 await 工作方式。 You need to assign a promise to results and to avoid
then
callback chaining we can use async/await
to get the response.您需要分配承诺的结果并避免
then
回调链接,我们可以使用async/await
获得响应。
const arr = [1, 2, 3]; const results = Promise.all(arr.map(async (item) => { return item + 1; })); async function output () { console.log(await results); } output();
Like other answers have mentioned, async returns a promise.就像其他答案提到的那样,异步返回一个承诺。 Thats the reason you are getting
这就是你得到的原因
Promise { <pending> }
Irrespective of whether what you are doing makes sense, you could just use then on this promise that was returned like so不管你所做的是否有意义,你都可以在这样返回的承诺上使用then
const results = async () => await Promise.all( [1, 2, 3, 4, 5].map(async item => { return item + 1; }) ); results().then(e => console.log(e));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.