Skip to content

Instantly share code, notes, and snippets.

@benmccormick
Created December 24, 2015 03:26
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 benmccormick/93169ffa2ed0210122b8 to your computer and use it in GitHub Desktop.
Save benmccormick/93169ffa2ed0210122b8 to your computer and use it in GitHub Desktop.
Promise Examples
//Promises take a function that receives callbacks that can be run when an operation completes
let delay5Seconds = new Promise(function(resolve, reject) {
setTimeout(resolve, 5000);
});
//You can respond to the results of a successfully resolved Promise using the `then` function
delay5Seconds.then(function() {
console.log('This gets logged 5 seconds later')
});
// Fetch is a browser API that makes HTTP requests and wraps the reply in a Promise
// Promise responses can be chained, and errors can be caught
fetch('/some/data').then(getMessageFromData).then(displayMessage).catch(function() {
alert('Failed to load data');
});
function getMessageFromData(data) {
return data.message
}
function displayMessage(message) {
alert(message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment