等待 API 调用,然后再在 NodeJS 中继续



>我在异步和等待方面遇到了问题,在这里我试图从天气 API 获取天气,但在我的主函数 getWeather 中,我希望代码等待我的 http.get 完成,然后再继续。目前,您可以想象,控制台上的输出首先是"测试",然后是"伦敦温度是......"。我尝试了很多使用承诺和异步/等待的不同方式,但没有一种有效...... 有人知道如何先打印天气然后"测试"吗?感谢

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");

request包装在 Promise 中:

function requestAsync() {
return new Promise((resolver, reject) => {
// 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);
// request will done here!
resolver();
return;
} catch (error) {
console.error(error.message);
}
} else {
printError({ message: "ERROR status != 200" });
}
// request was failed!
reject();
});
});
})
}

并使用异步/等待调用requestAsync

async function getWeather(city) {
await requestAsync();
console.log('test');
}
getWeather("London");

试试这个:

getWeather = function(city){
return new Promise(async function(resolve, reject){
try{
var dataUrl = await http.get("http://api.openweathermap.org/data/2.5/weather?q="+ city +"&APPID=[API_ID]&units=metric";
resolve(dataUrl);
} catch(error) {
return reject(error);
}
})
};

最新更新