Last active
August 29, 2015 14:10
-
-
Save cdax/321d826dfe2bcdae225c to your computer and use it in GitHub Desktop.
A promise-style asynchronous function in Node
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 http = require('http'); | |
var Q = require('q'); | |
var download = function(url) { | |
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(); | |
//As an upside of using promises, we also get to track download progress using deferred.notify() | |
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); | |
}); | |
}); | |
return deferred.promise; | |
}; | |
//Calling download | |
downlaod('http://nodejs.org') | |
.then(function(page) { | |
console.log('Downloaded.'); | |
}, function(err) { | |
console.log(err); | |
}, function(progress) { | |
console.log('Downloading... (' + progress + '%)'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment