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