我正在寻找在两个地方使用异步操作结果的最佳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)处记录某事之前。
只需将您的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
它。