【问题标题】:Why are these promises not resolving?为什么这些承诺没有解决?
【发布时间】:2019-01-25 02:31:54
【问题描述】:

promise.all 中时我需要等待吗?这还有什么问题?

(async => {
    const result = Promise.all(
        await domainContext.get1(id),
        await domainContext.get2(id)
    ).then(r => r);
})();

我期待:

result = [get1_value, get2_value]

我明白了:

'{}'

【问题讨论】:

  • 你是如何测试它的?恕我直言,发布的代码似乎缺少明确的return result;
  • Promise.all 期望一个可迭代的作为参数。您正在传递两个参数。您是否打算将这些放在一组[] 中?

标签: javascript node.js promise async-await


【解决方案1】:

Promise.all 期望 array 作为单个参数,而不是其参数中的 Promises 列表。此外,如果您使用的是Promise.all,请不要在内部使用await - 这会违背目的,因为您将已解析值 的数组传递给Promise.all,而不是将一个 Promises 数组传递给它等待。另外,要定义不带参数的异步函数,需要在async之后添加一个空参数列表:

const get1 = () => Promise.resolve('get1');
const get2 = () => Promise.resolve('get2');
(async () => {
    const result = await Promise.all([
      get1(),
      get2(),
    ]);
    console.log(result);
})();

您也可以await result 数组中的每个项目,如下所示:

const get1 = () => Promise.resolve('get1');
const get2 = () => Promise.resolve('get2');
(async () => {
    const result = [
      await get1(),
      await get2(),
    ];
    console.log(result);
})();

这可能是您尝试执行的操作,但请注意,这会导致以串行而不是并行方式请求每个项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-09
    • 2015-11-10
    • 1970-01-01
    • 2015-11-11
    • 2017-05-08
    • 1970-01-01
    • 2019-04-29
    • 2017-08-12
    相关资源
    最近更新 更多