40

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

Kevin B
  • 94,570
  • 16
  • 163
  • 180
user2520969
  • 1,389
  • 6
  • 20
  • 30
  • 4
    Great and useful comment – user2520969 Nov 07 '17 at 13:22
  • 3
    Yes, promises and `async`/`await` syntax sugar - as you suggested in the tags - are the way to go. Have you tried applying them to your problem? Please show your efforts. – Bergi Nov 07 '17 at 13:29
  • Possible duplicate of [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Kevin B Nov 07 '17 at 19:37

1 Answers1

65

 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()
Abdul Rab Memon
  • 396
  • 5
  • 19
Ozgur
  • 3,738
  • 17
  • 34
  • 3
    I have been searching for a good explanation of Promise and finally found one! Thank you! – Porco Jul 25 '19 at 18:40
  • 15
    None of the two alternatives actually waits. In particular `a` returned by `await` is not 5. Instead it is a promise, which is just another way to require a callback. The right answer would be: you can not wait. – ceving Nov 09 '20 at 16:31
  • 2
    operation function doesn't need to have async before it, since its not using await. Its redundant since async makes it so that the function returns a promise, but operation() already is returning a promise. – Logan Cundiff Feb 02 '21 at 12:41