【问题标题】:async await promise.all map not resolving promises异步等待 promise.all 映射未解决承诺
【发布时间】:2019-09-29 21:07:03
【问题描述】:

我正在尝试使用 async await 在 map 函数中理解 Promise.all,但我似乎返回了未决的承诺,我不明白为什么

这是当我有一个 .then 来解决我的承诺时的工作代码

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 ]

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

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


console.log(results())

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

【问题讨论】:

  • 你不能像这样使用 async with map。抱歉,我正在打电话,所以明天我可能会给你一个解决方案。我之前偶然发现了这个问题并修复了它
  • 你必须等待结果console.log(await results())
  • 您实际上并没有在此处执行任何异步操作,因此不需要 promise 或 async/await。但基本上async 的全部目的是强制一个函数返回一个promise,所以它的返回值确实是一个promise 也就不足为奇了!

标签: javascript node.js promise async-await


【解决方案1】:

使用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)
})();

【讨论】:

    【解决方案2】:

    您正在做的是为结果分配一个异步函数,这不是等待异步函数的工作方式。您需要为结果分配一个承诺并避免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();

    【讨论】:

      【解决方案3】:

      就像其他答案提到的那样,异步返回一个承诺。这就是你得到的原因

       Promise { <pending> } 
      

      不管你所做的是否有意义,你都可以在返回的这个 promise 上使用 then

      const results = async () =>
        await Promise.all(
          [1, 2, 3, 4, 5].map(async item => {
            return item + 1;
          })
        );
      
      results().then(e => console.log(e));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-09
        • 2018-04-17
        • 2020-04-21
        • 2021-12-26
        • 2018-07-19
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        相关资源
        最近更新 更多