Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

?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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...