我有一个使用一些异步函数的节点应用程序.
如何在继续执行其余应用程序流程之前等待异步函数完成?
下面有一个简单的例子.
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.
谢谢
解决方法
使用回调机制:
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 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()