Javascript 如何使用异步响应两次
我正在寻找在两个地方使用异步操作结果的最佳nodeJS实践 我目前有以下伪代码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
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.oreturn fetch(…)内容的程序。然后(()=>/*更新某些内容的新代码将在这里*/)
?或者再次使用async
和等待获取(…)
。不清楚您认为哪些内容需要使用两次。“如何访问fetchSomething()
中的something
”-fetchSomething()
是返回something
o内容的对象。在您的示例中,fetchSomething并没有返回承诺,而是返回我的something
对象。可以吗?我的理解是,只能等待返回承诺的函数。async
函数隐式地将其返回值包装在Promise
s中,以便等待它们。在您的示例中,fetchSomething不是返回承诺,而是返回我的something
对象。可以吗?我的理解是,只能等待返回承诺的函数。async
函数将其返回值隐式地包装在Promise
s中,以便等待它们。