2013-04-15 51 views
0

所以我在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 

所以我想,這個問題在這裏:如何使這個腳本等待回調函數返回值之前完成?

回答

1

這是因爲在節點的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); 
}); 
+0

輝煌。有效。非常感謝@robertklep! – nkcmr

1

看看在async serieshere,樣品在這裏

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 wait for multiple callbacks in Node.js

相關問題