nodejs从请求返回变量

时间:2016-03-22 15:48:49

标签: node.js variables express request

我正在使用快递。

在控制器中,我调用一个向URL发出请求的函数,然后重新启动HTML标记(使用cheerio)。即使所有console.log都有效,我也无法返回该值。

代码:

router.get('/', function(req, res) {
    var data = "none";
    var newData = parse(data);

    console.log(newData);
})



function parse(out){
    {
        url = 'http://www.XXXXXX.int/';
        out =  out || "Init value";
        request(url, out,  function(error, response, html){
            console.log(out);
            out ="ASDA";
            return out; //op1
        }) ;
        return out; //op2
    }

}

我能够检索标题var。但返回(甚至内部请求)返回不会修改原始值。它可能是同步的东西......但我真的迷失了......

任何光?¿

1 个答案:

答案 0 :(得分:2)

请求是异步的。您需要添加一个回调,这是标准的Node.JS架构

router.get('/', function(req, res) {
    var data = "none";
    var newData = "";
    parse(data , function( val ) {
         newData = val;
         console.log( "newData : " , newData );
         console.log( "this happens last" );
         // if you need to return anything, return it here. Do everything else you want to do inside this parse function.
         return res.sendStatus( 200 );
    } );
    console.log( "this happens first" );
});

function parse( out , callback ){
    url = 'http://www.XXXXXX.int/';
    out =  out || "Init value";
    request(url, out,  function(error, response, html){
        // don't you do anything with the error, response, html variables?
        console.log( "out : " , out);
        out ="ASDA";
        return callback( out ); //op1
   }) ;
}

这样做,你的输出应该是:

this happens first
out :  none
newData :  ASDA
this happens last