我正在尝试使用 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);
});
}