What is the correct way to handle nested async await calls in Node? [duplicate]

Async/Await only works on functions that return (and resolve) a promise.

The following example will write to the console after 3 seconds, and then continue on.

// Tell the browser that this function is asynchronous
async function myFunc() {
    // Await for the promise to resolve
    await new Promise((resolve) => {
        setTimeout(() => {
            // Resolve the promise
            resolve(console.log('hello'));
        }, 3000);
    });
    // Once the promise gets resolved continue on
    console.log('hi');
}

// Call the function
myFunc();

Without async/await, the output would be as follows:

hi
hello

Here is an example without async/await:

// Tell the browser that this function is asynchronous
async function myFunc() {
    // Skip await
    new Promise((resolve) => {
        setTimeout(() => {
            // Resolve the promise
            resolve(console.log('hello'));
        }, 3000);
    });
    // Since await was not used, this will print first
    console.log('hi');
}

// Call the function
myFunc();

This would be because the hi output would run and then after 3 seconds the timeout would run.

But with async/await, the output looks like this:

hello
hi

This is because we await for the timeout then we run the hi output.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)