【发布时间】:2013-04-15 17:42:42
【问题描述】:
所以我在node.js中有这个函数,它通过从https://icanhazip.com/获取外部IP(方便的网站,检查一下),但是当请求被调用时,它不允许在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
所以我想,这里的问题是:如何让这个脚本在返回值之前等待回调函数完成?
【问题讨论】:
标签: javascript node.js callback request