crazy4groovy
10/9/2016 - 1:21 AM

A strategy to synchronously execute a list of promises.

A strategy to synchronously execute a list of promises.

const fetch = require('node-fetch');

const queryParameters = ['ahoy', 'hello', 'hallo'];

const latestPromise = queryParameters.reduce((previousPromise, queryParam) => {
  return previousPromise.then(requestedUrlsSoFar => {
    return fetch(`http://httpbin.org/get?${queryParam}`)
      .then(response => response.json())
      .then(json => {
        // extract the URL property from the response object
        let url = json.url;
        console.log('Response from: %s', url);
        requestedUrlsSoFar.push(url);
        return requestedUrlsSoFar;
      });
  });
}, Promise.resolve([]));

latestPromise.then(allUrls => {
  console.log('The return values of all requests are passed as an array:');
  console.log(allUrls);
}).catch(error => {
  console.error('A call failed:');
  console.error(error.message);
});