与async / await一起使用时如何获得超出承诺的价值?

时间:2018-06-08 07:04:58

标签: node.js promise async-await

我正在尝试使用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 }

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

编辑:我正在尝试here的示例。检查"小心!避免过于连续的部分"。

3 个答案:

答案 0 :(得分:2)

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

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);
}

答案 1 :(得分:0)

async function doit() {
  const [ meta, data ] = await Promise.all([ call1(), call2() ])
  console.log(meta);
}

答案 2 :(得分:0)

函数需要返回Promise

'use strict';

async function doit() {

  let [meta,data] = await Promise.all([call1(),call2()]);

  console.log(meta);
}