首页 > 解决方案 > 与 async/await 一起使用时,如何从 Promise 中获得价值?

问题描述

我正在尝试使用 async/await 运行并行异步函数调用,但我不确定如何从异步调用中恢复返回的对象。

async function doit(){
  const meta = call1;   // async call 1
  const data = call2;   // async call 2
  await meta;
  await data;
  console.log(meta);

输出是

Promise { Returned value }

那么如何从异步调用中获取返回值呢?

编辑:我正在尝试从这里的例子。检查“小心!避免太顺序部分”。

标签: node.jspromiseasync-await

解决方案


如果您需要返回值,我会使用以下内容:

async function doit(){
  // create all async requests
  const metaReq = call1();   // async call 1
  const dataReq = call2();   // async call 2

  // wait for them
  const [meta, data] = await Promise.all( [ metaReq, dataReq ] );

  // use them
  console.log(meta);
}

推荐阅读