Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node wait for async function before continue

I have a node application that use some async functions.

How can i do for waiting the asynchronous function to complete before proceeding with the rest of the application flow?

Below there is a simple example.

var a = 0;
var b = 1;
a = a + b;

// this async function requires at least 30 sec
myAsyncFunction({}, function(data, err) {
    a = 5;
});

// TODO wait for async function

console.log(a); // it must be 5 and not 1
return a;

In the example, the element "a" to return must be 5 and not 1. It is equal to 1 if the application does not wait the async function.

Thanks

like image 267
user2520969 Avatar asked Nov 07 '17 13:11

user2520969


People also ask

How do you wait for an async function to finish?

Wait for function to finish using async/await keywords As you already know from the Promise explanation above, you need to chain the call to the function that returns a Promise using then/catch functions. The await keyword allows you to wait until the Promise object is resolved or rejected: await first(); second();

How do you wait for a function to finish in node JS?

Use async/await to Wait for a Function to Finish Before Continuing Execution. Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait .

How do you handle multiple asynchronous calls in node JS?

In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).


1 Answers

 Using callback mechanism:

function operation(callback) {

    var a = 0;
    var b = 1;
    a = a + b;
    a = 5;

    // may be a heavy db call or http request?
    // do not return any data, use callback mechanism
    callback(a)
}

operation(function(a /* a is passed using callback */) {
    console.log(a); // a is 5
})

 Using async await

async function operation() {
    return new Promise(function(resolve, reject) {
        var a = 0;
        var b = 1;
        a = a + b;
        a = 5;

        // may be a heavy db call or http request?
        resolve(a) // successfully fill promise
    })
}

async function app() {
    var a = await operation() // a is 5
}

app()
like image 50
Ozgur Avatar answered Oct 24 '22 07:10

Ozgur