NodeJs函数等待直到回调返回值

时间:2019-03-04 12:53:55

标签: node.js

我想在函数调用之外打印var a的值。如果我运行此程序,它将打印undefined

var http = require('http');

var foo = function(req, res){
    var a = xyz('5',function(aa){
        console.log(aa);
        return aa;
    });
    res.end(a);
    console.log(a);
}

function xyz(arg,callback){
    var aa = 55;
    return callback(aa);
}

http.createServer(foo).listen(8000);
console.log('start server');

1 个答案:

答案 0 :(得分:0)

使函数异步,然后等待xyz()

var http = require('http');

var foo = async function(req, res){
  var a = await xyz('5'); 
  res.end(a);
  console.log(a);
}

function xyz(arg){
  var aa = 55;
  return aa;
}

http.createServer(foo).listen(8000);
console.log('start server');