简体   繁体   中英

Is node.js asynchronous by default?

I am well versed with node.js, been working with JS since 2 years. But I still have confusion with asynchronous nature in node. Take a look at the following code

// Synchronous Code:

function foo() {
    const result1 = bar();
    console.log(result1);

    const result2 = see();
    console.log(result2);
}
function bar() {
    return 'bar';
}
function see() {
    return 'see'
}
foo();
// Result:
// bar
// see
// Asynchronous - I know async keyword returns a promise so i am resolving it
async function foo() {
    const result1 = await bar();
    console.log(result1);

    const result2 = await see();
    console.log(result2);
}
async function bar() {
    return 'bar';
}
async function see() {
    return 'see'
}
foo();
// Result:
// bar
// see

I see that both the scenarios perform similarly, am i missing anything or are async functions queued up in event loop?

Async functions are queued up in event loop but you can only use await in an async function. A top level async functions is run synchronously.

The body of an async function can be thought of as being split by zero or more await expressions. Top-level code, up to and including the first await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#description

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