异步等待 Promise.all 映射未解析 Promise

Ali*_*lil 1 javascript node.js promise async-await

我试图使用 async wait 来理解 Map 函数中的 Promise.all 但我似乎返回了待处理的 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))
Run Code Online (Sandbox Code Playgroud)

按预期记录 = [ 2, 3, 4, 5, 6 ]

现在要使用 async-await 实现该函数,我知道我需要使用关键字 async 将该函数包装在一个异步函数中,并等待 Promise.all

const results = async () => await Promise.all(arr.map(async (item) => {
    return item + 1;
}));


console.log(results())
Run Code Online (Sandbox Code Playgroud)

但我似乎总是记录Promise { <pending> }我不明白我做错了什么

Ber*_*rgi 5

使用asnyc/await不会使results函数同步。(它的字面意思是标记为async!)所以它返回一个承诺,你必须await在记录值之前这样做:

const arr = [1, 2, 3];

const results = Promise.all(
  arr.map(async item => item + 1)
);

(async () => {
  console.log(await results)
})();
Run Code Online (Sandbox Code Playgroud)