Javascript 如何使用异步响应两次

Javascript 如何使用异步响应两次,javascript,node.js,Javascript,Node.js,我正在寻找在两个地方使用异步操作结果的最佳nodeJS实践 我目前有以下伪代码 async function doSomething() { const something = await fetchSomething(); console.log("something", something); // (A) } function fetchSomething() { const promise = fetch("http://example.com

我正在寻找在两个地方使用异步操作结果的最佳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()
中的
something
行中进行更改,以更新
something
。新代码类似于
something.timestamp=newdate()


如何访问
fetchSomething()
中的
something
,并确保在(A)中记录某个内容之前,我对(B)中的某个内容进行了更新。

只需将
fetchSomething
转换为
异步即可:

异步函数doSomething(){ const something=等待获取某物(); console.log(“某物”,某物);/(A) } 异步函数fetchSomething(){ const something=等待获取(“http://example.com/something"); /*更新某些内容的新代码将在此处生效(B)*/ something.something='updated something!'; 归还某物; }

每个
async
函数都返回一个
Promise
,因此您可以再次等待它。

只需将您的
fetchSomething
转换为
async

异步函数doSomething(){ const something=等待获取某物(); console.log(“某物”,某物);/(A) } 异步函数fetchSomething(){ const something=等待获取(“http://example.com/something"); /*更新某些内容的新代码将在此处生效(B)*/ something.something='updated something!'; 归还某物; }

每个
async
函数都会返回一个
Promise
,这样您就可以再次等待它了。

返回fetch(…)。然后(()=>/*更新某些内容的新代码将驻留在这里*/)
?或者再次使用
async
等待获取(…)
。不清楚您认为需要两次消费什么。“我如何访问
fetchSomething()
中的
something
”-
fetchSomething()
是返回
something
o.o
return fetch(…)内容的程序。然后(()=>/*更新某些内容的新代码将在这里*/)
?或者再次使用
async
等待获取(…)
。不清楚您认为哪些内容需要使用两次。“如何访问
fetchSomething()
中的
something
”-
fetchSomething()
是返回
something
o内容的对象。在您的示例中,fetchSomething并没有返回承诺,而是返回我的
something
对象。可以吗?我的理解是,只能等待返回承诺的函数。
async
函数隐式地将其返回值包装在
Promise
s中,以便等待它们。在您的示例中,fetchSomething不是返回承诺,而是返回我的
something
对象。可以吗?我的理解是,只能等待返回承诺的函数。
async
函数将其返回值隐式地包装在
Promise
s中,以便等待它们。