0

我正在尝试使用 Mongoose 在 Node.js 中使用一个函数,该函数是用于 HTTP 请求的 .save 函数,我正在尝试提取地理坐标并将它们保存为 MongoDB 中 Mongoose Schema 中的数组。但是,我似乎遇到了同步问题,因为坐标最初打印为未定义,我必须刷新页面才能显示它们。我认为回调会解决这个问题,但他们没有。(我在下面添加了相关的代码片段。)我是在回调中做错了什么,还是应该做其他事情?提前致谢!

ArticleProvider.prototype.save = function(articles, callback) {
for( var i =0;i< parties.length;i++ ) {
    article = articles[i];
    article._id = articleCounter++;
    article.created_at = new Date();
if (article.coords === undefined){
      geocode(article.address, function(results){
        article.coords = results;
      });
}
 callback(null, articles);
};

var geocoder = require('Geocoder');
function geocode(address, callback) {
    geocoder.geocode( address, function( err , data) {
         // console.log(data.results[0].geometry.location);
          //console.log( [data.results[0].geometry.location.lng, data.results[0].geometry.location.lat]);
          var coords = [data.results[0].geometry.location.lng, data.results[0].geometry.location.lat];
        console.log(coords);
        callback(coords);
    });
}
4

1 回答 1

1

您在调用回调callback(null, articles);之前geocode调用回调。在调用回调之前,您需要确保所有这些都完成。我通常会推荐一个异步库,例如Caolan 的 async(查看async.forEach),但对于它的单个案例可能是矫枉过正。我会建议:

ArticleProvider.prototype.save = function(articles, callback) {
  var finishedCount = 0;
  var finishedOne = function() {
    finishedCount++;
    if(finishedCount == parties.length)
      callback(null, articles);
  };
  for( var i =0;i< parties.length;i++ ) {
    article = articles[i];
    article._id = articleCounter++;
    article.created_at = new Date();
    if (article.coords === undefined){
      geocode(article.address, function(results){
        article.coords = results;
        finishedOne();
      });
    }
    else {
      finishedOne();
    }
  }
};

我还修复了您的括号不匹配问题,我认为这是复制/粘贴错误。

于 2013-01-30T04:21:06.120 回答