0

所以我在node.js中有这个函数,它通过从(方便的网站,检查一下)获取外部IP https://icanhazip.com/,但是当请求被调用时,它不允许在return被调用之前完成。这是代码:

var request = require('request');
var get_ext_ip = function(){
    var _ip; //Initialize a return variable

    //Launch an HTTPS request to a simple service that shows IP of client
    //The callback function isn't allowed to finish.
    request('https://icanhazip.com', function(error, response, body){
        _ip = body; //when finished store the response in the variable that is going to be returned.
    });

    //Return
    return _ip;
}

var ip = get_ext_ip();
console.log(ip); //undefined

所以我想,这里的问题是:如何让这个脚本在返回值之前等待回调函数完成?

4

2 回答 2

1

看看这里的async series图书馆,这里的样本

async.series([
    function(callback){
        // do some stuff ...
        callback(null, 'one');
    },
    function(callback){
        // do some more stuff ...
        callback(null, 'two');
    }
],
// optional callback
function(err, results){
    // results is now equal to ['one', 'two']
});


// an example using an object instead of an array
async.series({
    one: function(callback){
        setTimeout(function(){
            callback(null, 1);
        }, 200);
    },
    two: function(callback){
        setTimeout(function(){
            callback(null, 2);
        }, 100);
    }
},
function(err, results) {
    // results is now equal to: {one: 1, two: 2}
});

另外,看看这个问题,Idiomatic way to waiting for multiple callbacks in Node.js

于 2013-04-15T17:45:50.733 回答
1

这是因为 Node 中 I/O 请求的异步特性:函数get_ext_ip在请求完成之前返回。

处理此问题的方法之一是传递一个回调函数,该回调函数将在请求完成时被调用:

var request = require('request');
var get_ext_ip = function(callback) {
  request('https://icanhazip.com', function(error, response, body) {
    callback(error, body);
  });
}

get_ext_ip(function(err, ip) {
  if (err)
    console.log('an error occurred:', error);
  else
    console.log(ip);
});
于 2013-04-15T17:48:45.350 回答