Created
August 28, 2016 15:29
-
-
Save azs06/6bb8fe78bba2ac9bffa3062db34543f9 to your computer and use it in GitHub Desktop.
Learnyounode juggling async solution using es6 promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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