本文介绍了节点在继续之前等待异步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个节点应用程序使用一些异步函数。
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;
在示例中,元素 a
返回必须是5而不是1.如果应用程序没有等待异步函数,它等于1。
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.
谢谢
推荐答案
使用回调机制:
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
})
使用async等待
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()
这篇关于节点在继续之前等待异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!