node.js - 与 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 }
那么如何从异步调用中获取返回值呢?
编辑:我正在尝试从这里的例子。检查“小心!避免太顺序部分”。
解决方案
如果您需要返回值,我会使用以下内容:
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);
}
推荐阅读
- java - 给定数组中的 n 个集合,查找所有相交集合对
- c++ - Gradle cpp 插件不链接共享库
- c++ - 如何通过串行终端检索数据而不破坏其在 GNU ARM 嵌入式中的基本价值?
- c# - 带有组合框和 listView 的 UserControl
- phpmailer - 如何将网站徽标和身份图像设计放在通过 phpmailer 发送到 gmail 的电子邮件的最顶部
- c++ - DirectX:“空样本”编译错误 (x86) - 1 个未解决的错误
- r - 如何连接到我在 Azure 数据工作室、R 工作室中查看的数据库?
- r - R 收益率曲线包以天为单位提取期限利率
- javascript - 如何使用材料箱
- ios - “idleTimerDisabled”如何在 didFinishLaunchingWithOptions 中工作?