api 调用返回未定义后的 Meteor 方法
Meteor method after api call returning undefined
我正在使用 Meteor,每当我对 googles geocode 进行 api 调用并尝试从中获取 return 值时,我得到一个未定义的值,我正在使用 api 所以那里肯定有数据,所以我不确定是什么原因造成的
callWeather = e => {
e.preventDefault();
console.log(this.state.address);
Meteor.call("geCoordinates", this.state.address, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
};
geCoordinates(address) {
googleMapsClient.geocode({ address }, (error, data) => {
if (error) {
console.log(error);
} else {
console.log(data.json.results[0].geometry.location.lat);
return data.json.results[0].geometry.location.lat;
}
});
},
这是大多数人在开始时都会犯的一个常见错误。这里的问题是,在你的方法代码执行回调函数之前,客户端中存在数据响应。这个有很多解决办法:
但是,我建议您使用 Meteor.wrapAsync
,如下所示:
let getGeoCode = Meteor.wrapAsync(googleMapsClient.geocode, googleMapsClient.geocode),
data = getGeoCode({ address }); // data contains data of your callback
我正在使用 Meteor,每当我对 googles geocode 进行 api 调用并尝试从中获取 return 值时,我得到一个未定义的值,我正在使用 api 所以那里肯定有数据,所以我不确定是什么原因造成的
callWeather = e => {
e.preventDefault();
console.log(this.state.address);
Meteor.call("geCoordinates", this.state.address, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
};
geCoordinates(address) {
googleMapsClient.geocode({ address }, (error, data) => {
if (error) {
console.log(error);
} else {
console.log(data.json.results[0].geometry.location.lat);
return data.json.results[0].geometry.location.lat;
}
});
},
这是大多数人在开始时都会犯的一个常见错误。这里的问题是,在你的方法代码执行回调函数之前,客户端中存在数据响应。这个有很多解决办法:
但是,我建议您使用 Meteor.wrapAsync
,如下所示:
let getGeoCode = Meteor.wrapAsync(googleMapsClient.geocode, googleMapsClient.geocode),
data = getGeoCode({ address }); // data contains data of your callback