1

I am trying to make multiple API calls based on the information in an array. For example, I have an array of ['London', 'New York', 'Mexico', 'China', 'Tokyo']

I want to get all the weathers using open weather api. I am trying to use promise.all. I need all the data back before rendering to the front, but my code isn't working.

let cities = ['London', 'New York', 'Mexico', 'China', 'Tokyo'] 
let promisesArray = []
return new Promise(function(resolve, reject) {
    for(let i = 0; i < cities.length; i++) {

        let cities = ['London', 'New York', 'Mexico', 'China', 'Tokyo'] 
        let url = 'api.openweathermap.org/data/2.5/weather?q=' + cities[i]
        request(url, function(error, response, body){

            if (err) {
                reject(error);
            }

            var data = JSON.parse(body)
            var results = data.Search;
            promisesArray.push(resolve(results));
        });

    }
})

    Promise.all(promisesArray)
        .then(function(results) {

        })
        .catch(function(error) {

        })
1
  • Why you use return ? If inside of function, Promise.all in your code won't run. Commented Jul 10, 2018 at 1:44

1 Answer 1

6

You have a couple things mixed up but it's the right idea. Your promiseArray needs to contain promises, not the data.

So you should go through your cities, create a promise for each, inside the promise call request and when the request returns call resolve. This is a little cleaner with array.map than a for loop.

Here's an example with a mocked request function:

// fakes request
function request(url, cb) {
  setTimeout(() => cb(null, 200, `{"Search": "success for ${url}" }`), 200)
}


let cities = ['London', 'New York', 'Mexico', 'China', 'Tokyo']

// promisesArray will hold all the promises created in map()
let promisesArray = cities.map(city => {
  // make a new promise for each element of cities
  return new Promise((resolve, reject) => {
    let url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city
    request(url, function(error, response, body) {
      if (error) {
        reject(error);
      }
      var data = JSON.parse(body)
      var results = data.Search;
      // resolve once we have some data
      resolve(results);
    });
  })
})

Promise.all(promisesArray)
  .then(function(results) {
    console.log(results)
  })
  .catch(function(error) {
    console.log(error)
  })

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.