node.js,无法从内部函数返回结果

时间:2011-11-20 11:04:07

标签: javascript node.js

我已经完成了这个功能,使用地理编码器模块,从几个纬度/长度获得城市:

// Get city from lat/long pair
function getCityFromCoordinates(lat, long){
 return geocoder.reverseGeocode(lat,long, function ( err, data ) {
    var city = "-";
    if(err){
       city = err.message;
    } else {
       if(data["results"].length == 0){ 
          city = "not found";
       } else {
          city = "";
          var first_item = data["results"][0];
          var address_components = first_item["address_components"];
          for (var i=0; i<address_components.length;i++){
             var current = address_components[i];
             var types = current["types"];
             for (var j=0;j<types.length;j++){
                var type = types[j];
                if((type == "locality") && (city == "")){
                   city = current["long_name"];
                }
             }   
          }
       }
    }
    console.log("City:" + city);
    return city;
 }); 
 }

当我从另一个地方调用此函数时,它正确检索城市(我在日志中看到这个),但它不返回值。我确定这与嵌入了我的函数的geocoder.reserverGeocode函数相关联,但我无法解决这个问题。

1 个答案:

答案 0 :(得分:5)

geocoder.reverseGeocode是异步的,这意味着您无法return回调内的结果。尝试这样的事情:

function getCityFromCoordinates(lat, long, cb){
 return geocoder.reverseGeocode(lat,long, function ( err, data ) {
    var city = "-";
    if(err){
       return cb(err.message);
    } else {
       if(data["results"].length == 0){ 
          return cb("not found");
       } else {
          city = "";
          var first_item = data["results"][0];
          var address_components = first_item["address_components"];
          for (var i=0; i<address_components.length;i++){
             var current = address_components[i];
             var types = current["types"];
             for (var j=0;j<types.length;j++){
                var type = types[j];
                if((type == "locality") && (city == "")){
                   city = current["long_name"];
                }
             }   
          }
       }
    }
    console.log("City:" + city);
    cb(null, city);
 }); 
}

现在您可以在代码中使用它:

getCityFromCoordinates(lat, long, function(err, city) {
  if (err) {
    console.log('error: '+err);
  } else {
    console.log('result: '+city);
  }
});