Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save visualjeff/da9449988516a18fd8a1d789aa589ac7 to your computer and use it in GitHub Desktop.
Save visualjeff/da9449988516a18fd8a1d789aa589ac7 to your computer and use it in GitHub Desktop.
Promise.all usage with node-fetch sample code.
#!/usr/bin/env node
'use stict';
const fetch = require('node-fetch');
const urls = ['http://jsonplaceholder.typicode.com/posts/1',
'http://jsonplaceholder.typicode.com/posts/2',
'http://jsonplaceholder.typicode.com/posts/3',
'http://jsonplaceholder.typicode.com/posts/a',
'http://jsonplaceholder.typicode.com/posts/5'
];
const policyChanges = [];
urls.forEach((v, i, a) => {
policyChanges.push(fetch(a[i]).then(res => res.ok ? res.json() : Promise.reject(`FetchError: request to ${a[i]} returned: ${res.statusText}`)));
});
const processPolicyChanges = async(policyChanges) => {
const responses = await Promise.all(policyChanges).catch(err => console.log(`${err}`));
if (responses) { //If any promise fails responses will be undefined.
responses.map((res) => console.log(res));
} else {
console.log(`DEPLOYMENT FAILED!!!`);
}
}
processPolicyChanges(policyChanges);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment