[英]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.