0

Hi I am trying to fetch the weather through openwheather api and post it on a web page. However, in the process of testing this, I found a part that could cause problems.

var my_weather = {};
request.get(
  "http://api.openweathermap.org/data/2.5/weather?lat=37.3578631&lon=126.9395806&appid=40e3257323ba173186324d66fac45a1f",
  function (req, res) {
    data = JSON.parse(res.body);
    my_weather.weather_main = data.weather[0].main;
    my_weather.temp = Math.round(data.main.temp - 273);
    my_weather.humidity = data.main.humidity;
    console.log(my_weather);
  }
);

console.log(my_weather);

When this code is executed, the outer console.log() is executed before the console.log() in the request function, and an empty object is displayed. How to wait for the weather to be saved in the code above and then execute the code below it. Is there any? I tried using async await, but it didn't work, so please tell me how

  • Thanks for your help! –  May 17 '21 at 03:56
  • 1
    You cannot make Javascript "wait" for a non-blocking, asynchronous operation such as a network request to finish. Instead, you must use a callback, a promise or an event to communicate completion back to the caller. Meanwhile the function will return BEFORE the asynchronous operation is complete and the caller will use the callback, promise or event to know when the operation is done and what the final result is. See the question yours is marked a duplicate of for a full description of the options you have. – jfriend00 May 17 '21 at 04:10
  • I'll find out more based on what you said thank you –  May 17 '21 at 04:13

1 Answers1

0

You need to use await, more info can be found here.

Qi Wang
  • 84
  • 10