Skip to content

Instantly share code, notes, and snippets.

@carloscarvallo
Created April 3, 2016 22:25
Show Gist options
  • Save carloscarvallo/97ebee3663f0b1d5dc7efd6e89248de1 to your computer and use it in GitHub Desktop.
Save carloscarvallo/97ebee3663f0b1d5dc7efd6e89248de1 to your computer and use it in GitHub Desktop.
Basic throw for Promises in Javascript
var http = require('http');
var url = process.argv[2];
// ej: http://www.html5rocks.com/en/tutorials/es6/promises/story.json
function get(url) {
return new Promise(function(resolve, reject){
http.get(url, function (res) {
if (res.statusCode === 200) {
res.setEncoding('utf8');
res.on('data', function (raw) {
var result = raw;
resolve(result);
});
} else {
res.on('error', function(raw) {
var result = raw;
reject(result);
});
}
});
})
}
get(url).then(function(response) {
console.log("Exito!\n\n", response);
}, function(error) {
console.error("Fallo!\n\n", error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment