Javascript 节点在继续之前等待异步功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47158979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:45:28  来源:igfitidea点击:

Node wait for async function before continue

javascriptnode.jsasynchronouspromiseasync-await

提问by user2520969

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.

在示例中,a要返回的元素“ ”必须是 5 而不是 1。如果应用程序不等待异步函数,则它等于 1。

Thanks

谢谢

回答by Ozgur

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