【问题标题】:Wait for API call before proceeding in NodeJS在继续使用 NodeJS 之前等待 API 调用
【发布时间】:2018-10-23 09:04:13
【问题描述】:

我遇到了异步和等待的问题,在这里我试图从天气 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");

【问题讨论】:

    标签: javascript async-await


    【解决方案1】:

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

    并使用 async/await 调用requestAsync

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-16
        • 2015-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-17
        • 2020-02-25
        • 2011-10-09
        相关资源
        最近更新 更多