javascript - 在继续使用 NodeJS 之前等待 API 调用
问题描述
我有异步和等待的问题,在这里我试图从天气 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");
解决方案
尝试这个:
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);
}
})
};
推荐阅读
- java - 尝试通过 Httpurlconnection.setrequestmethod 使用 PATCH 时出现异常
- google-cloud-platform - 如何使用 Apache Beam 动态地将文件写入谷歌存储桶?
- r - 如何将NaN值添加到R中数据框的行名
- r - 整洁的评估,例如 mtcars %>% mutate(target := log(target))
- mysql - 获取按列 SQL 的计数百分比
- r - 将具有 NA 的行删除到特定的列和条件中
- python - 从实例属性动态继承所有 Python 魔术方法
- javascript - 来自模板对象的对象构造函数
- django - Django - 获取查询集中的字段列表
- database - 我如何在我的火力库中注入新数据,制作我自己的信息帖子