我还在学习javascript,尤其是nodejs,我想从节点地理编码器的res获取city的数据。这是我的代码:
const
nodeGeocoder = require('node-geocoder');
const
tes = require('./tes');
let
options = {
provider: 'google',
httpAdapter: 'https',
apiKey: myapi,
formatter: null
};
let geocoder = nodeGeocoder(options);
geocoder.reverse({
lat: tes.lat,
lon: tes.lon
})
.then( res => {
return city = res[0].administrativeLevels.level1long;
})
.catch( err => {
console.log(err);
})
console.log(city);
答案 0 :(得分:0)
使用回调函数或在里面做事.then()承诺
const
nodeGeocoder = require('node-geocoder');
const
tes = require('./tes');
let
options = {
provider: 'google',
httpAdapter: 'https',
apiKey: myapi,
formatter: null
};
let geocoder = nodeGeocoder(options);
geocoder.reverse({
lat: tes.lat,
lon: tes.lon
})
.then( res => {
city = res[0].administrativeLevels.level1long;
//do here whatever you want
})
.catch( err => {
console.log(err);
})
或制作回调函数
function getCity(callback){
geocoder.reverse({
lat: tes.lat,
lon: tes.lon
})
.then( res => {
city = res[0].administrativeLevels.level1long;
callback(null, city);
})
.catch( err => {
console.log(err);
callback(err);
})
}
使用上述功能
getCity(function(err, city){
if(err){
console.log(err);
}else{
console.log(city);
}
})