Node wait for async function before continue

前端 未结 1 449
青春惊慌失措
青春惊慌失措 2020-12-14 02: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 applic

相关标签:
1条回答
  • 2020-12-14 03:21

     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()
    
    0 讨论(0)
提交回复
热议问题