[英]How to use async and await correctly in nodejs?
當我運行console.log (f ())
我希望它返回來自getData (url)
,但它始終返回Promise {<pending>}
。 我認為使用await
關鍵字可以通過使代碼執行停止直到getData ()
返回某些內容來解決此問題。 我知道我是否使用f().then(console.log)
可以正常工作,但我只是不明白為什么console.log (f())
也不起作用。 有一種方法可以達到相同的結果f().then(console.log)
但不使用then ()
函數?
async function f() {
const url = `https://stackoverflow.com`;
let d = await getData(url);
return d;
}
console.log(f());
如果不可能,您能解釋為什么嗎?
async
和await
不會停止異步功能。
async
函數將始終返回Promise。 它只是解析為您return
任何內容,而不是要求您使用該值調用resolve
函數。
在async
函數中,您可以await
其他Promises。 這模擬了非異步代碼,但這僅僅是語法。 它不允許您執行then()
無法做的任何事情,它只是為您提供了一種更簡單的語法。
f
是一個異步函數,因此它仍然返回Promise。
要等待這個諾言解決,您需要await
它。
(async () => console.log(await f())();
或很長一段時間:
async function run(){
console.log(await f());
}
run();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.