所以我在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
所以我想,這個問題在這裏:如何使這個腳本等待回調函數返回值之前完成?
輝煌。有效。非常感謝@robertklep! – nkcmr