当我运行时,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());
如果不可能,您能解释为什么吗?
f
是一个异步函数,因此它仍然返回Promise。
要等待这个诺言解决,您需要兑现await
。
(async () => console.log(await f())();
或很长一段时间:
async function run(){
console.log(await f());
}
run();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句