Created
December 24, 2015 03:26
-
-
Save benmccormick/93169ffa2ed0210122b8 to your computer and use it in GitHub Desktop.
Promise Examples
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
//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