提问者:小点点

如何使用一个异步响应两次[关闭]


我正在寻找在两个地方使用异步操作结果的最佳nodeJS实践。

我当前有以下伪代码

async function doSomething() {
  const something = await fetchSomething();
  console.log("something", something); // (A)
}
function fetchSomething() {
   const promise = fetch("http://example.com/something");
   /* new code to update something will live here (B) */
   return promise;
}

到目前为止还不错

我现在需要做一个更改,以更新FetchSomething()new code will live here行的something。新代码类似于something.timestamp=new Date();

我如何访问FetchSomething()中的something,并确保我在(B)处对某事进行的更新发生在我在(A)处记录某事之前。


共1个答案

匿名用户

只需将您的FetchSomething转换为也是Async:

async function doSomething() {
  const something = await fetchSomething();
  console.log("something", something); // (A)
}

async function fetchSomething() {
    const something = await fetch("http://example.com/something");
    /* new code to update something will live here (B) */
    something.someOtherThing = 'updated something!';
    return something;
}

每个async函数都返回一个promise,因此您可以再次await它。

相关问题