所以我在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
所以我想,这里的问题是:如何让这个脚本在返回值之前等待回调函数完成?
最佳答案
这是因为 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);
});
关于javascript - 在有机会设置重要数据之前就忽略了函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16021448/