Created
March 28, 2014 23:15
-
-
Save cvan/9844927 to your computer and use it in GitHub Desktop.
async parsing data URIs remotely (with nested 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
var request = require('request'); | |
var Promise = require('es6-promise').Promise; | |
var promisesApps = []; | |
promisesApps.push(new Promise(function (resolveApp, rejectApp) { | |
var urls = [ | |
'https://marketplace-dev.mozflare.net/img/uploads/addon_icons/405/405402-64.png?modified=1384390457', | |
'https://marketplace-dev.mozflare.net/img/uploads/previews/full/81/81268.png?modified=1368635236' | |
]; | |
var promisesDataUris = []; | |
urls.forEach(function () { | |
var req = request(urls[0]); | |
promisesDataUris.push(new Promise(function (resolveDataUri, rejectDataUri) { | |
req.end(); | |
req.on('response', function (res) { | |
var body = ''; | |
var prefix = 'data:' + res.headers['content-type'] + ';base64,'; | |
res.setEncoding('binary'); | |
res.on('data', function (chunk) { | |
if (res.statusCode == 200) { | |
body += chunk; | |
} | |
}).on('end', function () { | |
var base64 = new Buffer(body, 'binary').toString('base64'); | |
var data = prefix + base64; | |
if (data) { | |
resolveDataUri(data); | |
} else { | |
rejectDataUri(data); | |
} | |
}).on('error', function () { | |
rejectDataUri(); | |
}); | |
}); | |
})); | |
}); | |
Promise.all(promisesDataUris).then(function (data) { | |
console.log('data URIs done'); | |
resolveApp(data); | |
}, function () { | |
console.log('data URIs error'); | |
rejectApp(); | |
}); | |
})); | |
Promise.all(promisesApps).then(function (data) { | |
console.log('app done', data); | |
}, function () { | |
console.log('app error'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment