Skip to content

Instantly share code, notes, and snippets.

@StanShumsky
Forked from hyjk2000/juggling-async-promise.js
Last active August 29, 2015 14:21
Show Gist options
  • Save StanShumsky/2bf42bfd863d3888600e to your computer and use it in GitHub Desktop.
Save StanShumsky/2bf42bfd863d3888600e to your computer and use it in GitHub Desktop.
var http = require('http')
, bl = require('bl')
, urls = process.argv.slice(2)
function httpGet(url) {
return new Promise(function (resolve, reject) {
http.get(url, function (response) {
response.pipe(bl(function (err, data) {
if (err) reject(err)
resolve(data.toString())
}))
}).on('error', function (e) {
reject(e)
})
})
}
// print results after all urls were loaded
Promise.all(urls.map(httpGet)).then(function (dataList) {
dataList.forEach(function (data) {
console.log(data)
})
}).catch(console.error)
// another way, print first result ASAP
urls.map(httpGet).reduce(function (sequence, urlPromise) {
return sequence.then(function () {
// wait for loading complete...
return urlPromise
}).then(function (data) {
console.log(data)
})
}, Promise.resolve())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment