我目前正试图绕过Node的异步性质。我目前正在试验Geocoder但是我似乎无法找出问题的根源。我当前的快递路由处理程序如图所示
app.get('/:location/:next_location', (req, res) => {
geocoder.geocode(req.params.location, function ( err, data ) {
if (err) {
console.log(err)
}
var location1, location2
location1 = data
console.log(location1.results[0].geometry)
geocoder.geocode(req.params.next_location, function (err, data) {
if (err) {
console.log(err)
}
location2 = data
console.log(location2.results[0].geometry)
});
res.send('Ok')
});
});
当我点击这条路线时,我正在
/Users/dannyxxx/Desktop/react/node-yelp/server.js:47
console.log(location2.results[0].geometry)
^
TypeError: Cannot read property 'geometry' of undefined
提前谢谢
更新
function geocodePromise(data){
return new Promise(function(resolve, reject){
geocoder.geocode(data, function (err, data) {
if (data) { resolve(data) }
})
})
}
var points = {}
geocodePromise(req.params.location)
.then((data)=> {
points.location1 = data.results[0].geometry.location
return geocodePromise(req.params.next_location)
})
.then(data => {
points.location2 = data.results[0].geometry.location
})