Skip to content

Instantly share code, notes, and snippets.

@cdax
Created November 24, 2014 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdax/d5eaf21cd1e17686c588 to your computer and use it in GitHub Desktop.
Save cdax/d5eaf21cd1e17686c588 to your computer and use it in GitHub Desktop.
Asynchronous function offering both a callback- as well as a promise-style API
var http = require('http');
var Q = require('q');
var download = function(url, callback) {
var page = '';
var deferred = Q.defer();
http.get(url, function(res) {
var page_size = res.headers['content-length'] || res.headers['Content-Length'];
res.on('data', function(chunk) {
page += chunk.toString();
deferred.notify(100 * page.length / page_size);
});
res.on('end', function() {
//Promise fullfilled
deferred.resolve(page);
});
res.on('error', function(err) {
//Promise rejected
deferred.reject(err);
});
});
//Registering the callback if present
if(callback)
deferred.promise.nodeify(callback);
return deferred.promise;
};
//Calling download and using the returned promise
downlaod('http://nodejs.org')
.then(function(page) {
console.log('Downloaded.');
}, function(err) {
console.log(err);
}, function(progress) {
console.log('Downloading... (' + progress + '%)');
});
//Calling download and passing in a callback
downlaod('http://nodejs.org', function(err, page) {
if(err)
console.log(err);
else
console.log('Downloaded.');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment