简体   繁体   中英

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 until getData () 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?

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM