Skip to content

Instantly share code, notes, and snippets.

@azs06
Created August 28, 2016 15:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azs06/6bb8fe78bba2ac9bffa3062db34543f9 to your computer and use it in GitHub Desktop.
Save azs06/6bb8fe78bba2ac9bffa3062db34543f9 to your computer and use it in GitHub Desktop.
Learnyounode juggling async solution using es6 promises
const http = require('http');
const urls = process.argv.slice(2, process.argv.length);
let fetchData = function(url){
return new Promise(function(resolve, reject) {
http.get(url, (res)=>{
let data = '';
res.setEncoding('utf8');
//res.resume();
res.on('data',(chunk)=>{
data += chunk;
});
res.on('end',()=>{
resolve(data);
})
}).on('error',(e)=>{
console.log(`error on: ${url}`);
console.log(`Got error: ${e.message}`);
reject(e);
});
});
}
let itemPromises = urls.map(fetchData);
Promise.all(itemPromises)
.then(function(results){
// we only get here if ALL promises fulfill
results.forEach(function(item) {
console.log(item);
// process item
});
}).catch(function(err){
console.log("Failed:", err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment