我试图调用天气API来获取机器人的当前天气。我使用node-rest-client来描述天气的描述,该描述将在context.forecast
中进行。唯一的问题是,我似乎无法修改/创建函数内部的变量或在函数外部访问它。这是我的代码:
'fetch-forecast': (sessionId, context, cb) => {
var url = "http://api.openweathermap.org/data/2.5/weather?q="+context.location+"&APPID=APIKEY";
var forecast;
Client.get(url, (data, response) => {
context.forecast = data.weather[0].description;
});
cb(context);
}
context.forecast
返回undefined。这样的事情似乎也不起作用:
'fetch-forecast': (sessionId, context, cb) => {
var url = "http://api.openweathermap.org/data/2.5/weather?q="+context.location+"&APPID=APIKEY";
var forecast;
Client.get(url, (data, response) => {
forecast = data.weather[0].description;
});
context.forecast = forecast;
cb(context);
}
context.forecast
也会在此处返回undefined。关于我做错什么的任何想法?
[编辑]尝试过类似的内容,但我仍然无法修改context.forecast
变量:
'fetch-forecast': (sessionId, context, cb) => {
var location = context.location;
var url = "http://api.openweathermap.org/data/2.5/weather?q="+location+"&APPID=APIKEY";
var forecast;
function getWeather(url) {
return new Promise(function(resolve, reject) {
Client.get(url, (data, response) => {
resolve(data.weather[0].description);
});
});
}
getWeather(url).then(function(result) {
context.forecast = result;
console.log(context.forecast)
}).catch(function() {
context.forecast = "not found";
});
console.log(context.forecast);
cb(context);
}
第二个console.log
首先返回undefined
,第一个console.log
返回实际值秒。我仍然不知道为什么会这样。