如何等待异步函数并收集响应

How to await on async function and collect the response

直到现在,我认为 await 让我的程序同步。但是,我看到 await 只等待 async 函数被承诺解决,然后整个程序继续 运行。那么,等待和收集异步函数响应的正确方法是什么?

原代码:

let result={
  name:'',
  country:''
};
const data = await query.getCachedData(did); 
result.name = data.name; // undefined
result.country = data.country;//undefined
console.log(result);

我不知道为什么,但等待异步函数结果有效:

let result={
  name:'',
  country:''
};
const data = await query.getCachedData(did); 
result.name = await data.name; //'Jon'
result.country = await data.country;// 'US'
console.log(result);

但我不确定这是否是解决方案。

因为 getCachedData returns 的承诺,我认为这可能是正确的方式,但 then()/catch() 没有执行。

query.getCachedData(did).then((tfnData) => {
  result.name = data.name; 
  result.country = data.country;
  console.log(result);
}).catch((dbError) => {
  console.log(dbError);
});

谁能纠正我 result 的正确方法?

你是正确的 await 等待 async 函数来 return 一个承诺。对于您的代码示例,我建议如下:

let result={
    name:'',
    country:''
};

async function getData() {
    const data = await query.getCachedData(did);
    result.name = data.name; // 'Jon'
    result.country = data.country; // 'US'
    console.log(result);
}

await 只能在 async 函数中使用。它将暂停该功能,直到收到来自 query.getCachedData() 的承诺,将该响应保存到 const data 中,然后可用于设置 result 对象的名称和国家/地区。您还可以查看 async and await.

的 MDN 文档

await 不会使您的异步代码同步 - 并且不应该有任何合理的理由这样做......在幕后它 returns 一个承诺并将它与 then 链接而不是你必须把它和你自己联系起来。

您使用 then 关键字所做的,就是 await 为您所做的。

您可以使用任何适合您的方式,但是 async/await 让您的代码更易于阅读。

如果这有效

result.name = await data.name; 

这意味着 name 是一个异步 getter 函数,您必须 await 才能得到结果.你也可以这样做 data.name.then(name => doWhateverYouWantWithName(name)) 或像您已经使用的那样使用 await 关键字 - 甚至应该更好。

Promise 是来自异步函数的 return。结果可能还没有完成。 这就是为什么你可以 await 一个方法(就像你做的那样)。这将在计算完成时从函数中设置 return。

或者您可以使用 'then':

const data1 = await query.getCachedData(did);
//data1 has a value at this point of code

const data2;
query.getChachedData(did).then((result)=>{data2 = result});
//data2 can have a value or will get one later (this is async) at this point of code

使用 Promise all,您可以让多个方法 运行 异步并同时等待所有方法。 https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

const callStack = [];

const data1;
const data2;
callStack.push(query.getChachedData(did).then((result)=>{data1 = result}));
callStack.push(query.getChachedData(did).then((result)=>{data2 = result}));
//run both query Methods at asynchronous 
await Promise.all(callStack);
//data1 and data2 hava a value at this point of code

Until now, I thought await makes my program synchronous

Async/await 使代码看起来像是同步的,但背后只是 语法糖 Javascript 中的承诺。 真的吗? Yes

就是return thePromise().then(result => result)

I see that await only waits for async function to be resolved with a promise then the whole programs continues to run

当您使用 promises 时,它们不会使 Node.js 代码 运行 同步,另一方面,promises 允许您编写看似同步的流程。

So, what is the right way to wait & collect the response from async function?

根据您的示例,代码将如下所示:

const queryResult = did => query.getCachedData(did).then(tfnData => tfnData);

// Without async/await    
queryResult(did)
  .then(data => {
    const { name, country } = data;
    const result = { name, country };
    console.log(`${result.name}, ${result.country}`); // Jon, US
  })
  .catch(error => console.log(`Error produced: ${error}`));

// With async/await
(async () => {
  try {
    // ... Some other code ....
    // ... Some other code ....
    // ... Some other code ....

    const data = await queryResult(did);
    const { name, country } = data;
    const result = { name, country };
    console.log(`${result.name}, ${result.country}`); // Jon, US
  } catch (error) {
    console.log(`Error inside try-catch: ${error}`);
  }
})();