首页 > 解决方案 > 在继续使用 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");

标签: javascriptasync-await

解决方案


尝试这个:

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

推荐阅读