【发布时间】:2018-10-23 09:04:13
【问题描述】:
我遇到了异步和等待的问题,在这里我试图从天气 API 获取天气,但在我的主函数 getWeather 中,我希望代码在继续之前等待我的 http.get 完成。目前,您可以想象,控制台上的输出首先是“test”,然后是“In London temperature is ...”。我尝试了很多不同的方式来使用 Promise 和 async/await 但它们都不起作用...... 有人知道如何先打印天气然后“测试”吗?谢谢
var http = require('http');
function printMessage(city, temperature, conditions){
var outputMessage = "In "+ city.split(',')[0] +", temperature is
"+temperature+"°C with "+conditions;
console.log(outputMessage);
}
function printError(error){
console.error(error.message);
}
function getWeather(city){
var request = http.get("http://api.openweathermap.org/data/2.5/weather?q="+ city +"&APPID=[API_ID]&units=metric", function(response){
var body = "";
response.on('data', function(chunk){
body += chunk;
});
response.on('end', function(){
if (response.statusCode === 200){
try{
var data_weather = JSON.parse(body);
printMessage(city, data_weather.main.temp, data_weather.weather[0].description);
} catch(error) {
console.error(error.message);
}
} else {
printError({message: "ERROR status != 200"});
}
});
});
console.log('test');
}
getWeather("London");
【问题讨论】: