Skip to content

Instantly share code, notes, and snippets.

@danlourenco
Created March 3, 2016 20:08
Show Gist options
  • Save danlourenco/c174d541047931d11cb7 to your computer and use it in GitHub Desktop.
Save danlourenco/c174d541047931d11cb7 to your computer and use it in GitHub Desktop.
Promise patterns from HTML5Rocks
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
// Like "throw" in plain old JavaScript, it's customary, but not required, to reject with an Error object.
// The benefit of Error objects is they capture a stack trace, making debugging tools more helpful.
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
// "then" takes two arguments, a callback for a success case, and another for the failure case.
// Both are optional, so you can add a callback for the success or failure case only.
//Error handling:
get('story.json').then(function(response) {
console.log("Success!", response);
}, function(error) {
console.log("Failed!", error);
});
// -OR -
get('story.json').then(function(response) {
console.log("Success!", response);
}).catch(function(error) {
console.log("Failed!", error);
});
// There's nothing special about "catch", it's just sugar for then(undefined, func), but it's more readable.
// Note that the two code examples above do not behave the same, the latter is equivalent to:
get('story.json').then(function(response) {
console.log("Success!", response);
}).then(undefined, function(error) {
console.log("Failed!", error);
});
// http://www.html5rocks.com/en/tutorials/es6/promises/#toc-async
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment