当我运行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());
如果不可能,你能解释为什么吗?
答案 0 :(得分:3)
async
和await
不会阻止函数异步。
async
函数将始终返回一个Promise。它只是解析为您的return
内容,而不是要求您使用值调用resolve
函数。
在async
函数中,您可以await
其他承诺。这可以模拟非异步代码,但这只是语法。它不会让您做then()
做不到的任何事情,它只是为您提供了一种更简单的语法。
答案 1 :(得分:3)
f
是一个异步函数,因此它仍然返回Promise。
要等待此承诺解决,您需要await
。
(async () => console.log(await f())();
或者很长:
async function run(){
console.log(await f());
}
run();