1

I want build a function that gets the forecast weather descriptions of four cities using the Open Weather Map API. The cities are placed in a list in a variable called "cities". I think I must create a for loop to run all cities through the API?

The result should be a list where all cities show 8 weather descriptions of the next 8 days.

This is what I have so far. Any suggestions?

function getDescriptions(){
    
    var cities = [Cannes, London, Amsterdam, Berlin];
        
    $.ajax({
        url: 'http://api.openweathermap.org/data/2.5/forecast/daily?q=' + city + "&units=metric" + "&cnt=8" + "&APPID=***",
        type: "GET",
        dataType: "jsonp",
        success: function(data){         
            
            var descriptions = data.list[i].weather[0].description;            
        
        }                       
    });        
}
James Miller
  • 121
  • 2
  • 12

2 Answers2

3

The thing that will trip you up is that the ajax call is asynchronous, so you cant just "return" the results. (See How do I return the response from an asynchronous call?)

So your getDescriptions will need to return a promise which resolves when all of the ajax calls are completed.

function getDescriptions(cities){

  var requests = cities.map(function(city){
      return $.ajax({
        url: 'http://api.openweathermap.org/data/2.5/forecast/daily?q=' + city + "&units=metric" + "&cnt=8" + "&APPID=***",
        type: "GET",
        dataType: "jsonp"       
      }).then(function(data){
           return data.weather[0].description
      });     
  });

  return Promise.all(requests);
   
}

var cities = ["Cannes", "London", "Amsterdam", "Berlin"];
getDescriptions(cities).then(function(results){
    console.log(results);
});
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

I think your best way is to push all city's to the api and then get all the details in return, but i'm guessing that will not work.

How about an object?

function getDescriptions(){

    var cities = {
    'Cannes': '', 'London': '', 'Amsterdam': '', 'Berlin': ''} 
    for (var city in cities) {
       $.ajax({
          url: 'http://api.openweathermap.org/data/2.5/forecast/daily?q=' + city + "&units=metric" + "&cnt=8" + "&APPID=***",
          type: "GET",
          dataType: "jsonp",
          success: function(data){         
              cities[city] = data.weather[0].description;            

          }                       
      });  
      document.write(city+ "- " + cities[city])
    }
}
Nebulosar
  • 1,727
  • 3
  • 20
  • 46