等待API调用,然后再继续执行NodeJS

时间:2018-10-23 09:04:14

标签: javascript async-await

我在异步和等待方面遇到问题,这里我试图从天气API中获取天气,但是在我的主要功能getWeather中,我希望代码在继续操作之前先等待http.get完成。您可以想象,目前,控制台上的输出首先是“测试”,然后是“伦敦的温度是...”。我尝试了很多使用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");

2 个答案:

答案 0 :(得分:0)

尝试一下:

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

答案 1 :(得分:0)

request包装在一个诺言中:

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

并使用async / await呼叫requestAsync

async function getWeather(city) {
    await requestAsync();

    console.log('test');
}

getWeather("London");
相关问题