Skip to content

Instantly share code, notes, and snippets.

@zladuric
Created October 25, 2017 08:28
Show Gist options
  • Save zladuric/0941f20a885d30f4a5e9c30ff01131fe to your computer and use it in GitHub Desktop.
Save zladuric/0941f20a885d30f4a5e9c30ff01131fe to your computer and use it in GitHub Desktop.
const request = require('request');
function callRemoteApi(url) {
return new Promise((resolve, reject) => {
console.log('Fetching', url);
request(url, (err, res) => {
if (err) {
return reject(err);
}
console.log('Got', url);
const result = JSON.parse(res.body).url;
resolve(result);
});
});
}
async function runTest() {
const urls = [
'https://httpbin.org/delay/5',
'https://httpbin.org/delay/1',
'https://httpbin.org/delay/3',
];
await forLoopExample(urls);
await promiseAllExample(urls);
console.log('Done with all examples.');
}
async function forLoopExample(urls) {
console.log('Run for loop example');
let promises = [];
for (let url of urls) {
console.log(await callRemoteApi(url));
}
console.log('Done for loop example\n');
}
async function promiseAllExample(urls) {
console.log('Run promise.all example');
let promises = [];
for (let url of urls) {
promises.push(callRemoteApi(url));
};
await Promise.all(promises)
.then(result => console.log('Result of all promises:', result))
console.log('Done promise.all example.\n');
}
runTest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment