У меня проблема с асинхронностью и ожиданием, здесь я пытаюсь получить погоду из API погоды, но в своей основной функции getWeather я хочу, чтобы код ожидал выполнения моего http.get, прежде чем продолжить.На данный момент, как вы можете себе представить, вывод на консоли сначала «тест», а затем «В Лондоне температура ...».Я пробовал довольно много разных способов использования обещаний и асинхронного ожидания, но ни один из них не работает ... Кто-нибудь знает, как сначала распечатать погоду, а затем "проверить"?Thx
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");