Created
April 3, 2016 22:25
-
-
Save carloscarvallo/97ebee3663f0b1d5dc7efd6e89248de1 to your computer and use it in GitHub Desktop.
Basic throw for Promises in Javascript
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 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