MeteorJS:无法分配变量

MeteorJS: Can not assign a variable

我有这样的代码,想在函数中将一个变量赋值给另一个变量,代码示例:

Meteor.methods({
              parsing:function(){
                var aa ;
                request("https://google.com/", function(error, response, body) {
                    if (!error && response.statusCode == 200) {
                          var k=1;
                          aa = k;
                    }
                });
                console.log(aa);
              }
});

已记录 undefined,有人可以解释一下原因吗?

编辑:

 Meteor.methods({
                  parsing:function(){
                    var aa ;
                    var tmp;
                    request("https://google.com/", function(error, response, body) {
                        if (!error && response.statusCode == 200) {
                              var k=1;
                              aa = k;
                              console.log(aa);
                              request("https://google.com/xyz", function(error, response, body) {
                                tmp = response.request.uri.href;
                              });
                        }
                        console.log(tmp);
                    });

                  }
    });

例如我需要 console.log(tmp); 只有当我的第二个请求将被调用(结束)

您作为 request 参数提供的函数将仅在请求从 Google 获得答案时执行。但是代码的下一部分(您的 console.log 行)仍然执行而无需等待任何东西。

如果你想在你的日志之前等待请求结果,将它添加到你的函数中:

parsing:function(){
    var aa ;
    request("https://google.com/", function(error, response, body) {
        if (!error && response.statusCode == 200) {
              var k=1;
              aa = k;
              console.log(aa);
        }
    });
}

编辑:

好吧,您可以根据需要多次使用相同的技巧:

parsing:function(){
    var aa ;
    var tmp;
    request("https://google.com/", function(error, response, body) {
        if (!error && response.statusCode == 200) {
            var k=1;
            aa = k;
            console.log(aa); // Waited the first answer.
            request("https://google.com/xyz", function(error, response, body) {
                tmp = response.request.uri.href;
                console.log(tmp); // Waited the second one.
            });
        }
    });

}