Reputation: 365
When i run console.log (f ())
i want it returns the data that came from getData (url)
, but it keeps returning Promise {<pending>}
. I thought using await
keyword would solve this by making the code execution stops untilgetData ()
returns something. I know if i use f().then(console.log)
it will work fine, but i just don't understand why console.log (f())
does not works too.
There is a way to achieve the same result f().then(console.log)
but not using the then ()
function?
async function f() {
const url = `https://stackoverflow.com`;
let d = await getData(url);
return d;
}
console.log(f());
If it is impossible, can you explain why?
Upvotes: 2
Views: 211
Reputation: 7346
f
is an async function, so it still returns a Promise.
To wait for this promise to resolve you need to await
it.
(async () => console.log(await f())();
Or in long:
async function run(){
console.log(await f());
}
run();
Upvotes: 3
Reputation: 944320
async
and await
do not stop functions from being asynchronous.
An async
function will always return a Promise. It just resolves to whatever you return
instead of requiring that you call resolve
function with the value.
Inside an async
function, you can await
other Promises. This simulates non-asynchronous code, but it is just syntax. It doesn't let you do anything you couldn't do with then()
, it just gives you a simpler syntax.
Upvotes: 3