Bruno Brito
Bruno Brito

Reputation: 365

How to use async and await correctly in nodejs?

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

Answers (2)

Sebastian Speitel
Sebastian Speitel

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

Quentin
Quentin

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

Related Questions