问题描述
我正在尝试使用async await在map函数中理解Promise.all,但我似乎返回的是未决的Promise,我不明白为什么
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
这是我有一个.then解决我的诺言时的工作代码
Here is the working code when i have a .then to resolve my promise
const arr = [1, 2, 3, 4, 5];
const results = Promise.all(arr.map( item => {
return item + 1;
}));
results.then(result=> console.log(result))
按预期记录的日志= [2,3,4,5,6]
which logs as expected = [ 2, 3, 4, 5, 6 ]
现在要使用async-await来实现该功能,我知道我需要使用关键字async将功能包装在async功能中,并等待promise.all
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
const results = async () => await Promise.all(arr.map(async (item) => {
return item + 1;
}));
console.log(results())
但是我似乎总是登录Promise { <pending> }
我不明白我在做什么错
but i always seem to log Promise { <pending> }
I don't understand what im doing wrong
推荐答案
使用asnyc
/await
不会使results
函数同步. (它的字面标记为async
!)因此它返回一个promise,在记录值之前必须先await
:
Using asnyc
/await
doesn't make the results
function synchronous. (It's literally tagged as async
!) So it returns a promise, and you have to await
that before logging the values:
const arr = [1, 2, 3];
const results = Promise.all(
arr.map(async item => item + 1)
);
(async () => {
console.log(await results)
})();
这篇关于异步等待promise.all地图不解决promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!