Last active
May 30, 2017 03:00
-
-
Save bdunn313/d30d676d2333dbd5b57944638f332dbc to your computer and use it in GitHub Desktop.
Promise Example
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
// Simulate a network request by using setTimeout | |
// This achieves the same thing as our version above. | |
// This time though, we are going to return a Promise! | |
function fakeNetworkCall(url) { | |
const promise = new Promise((resolve, reject) => { | |
setTimeout(() => resolve(url), 1500); | |
}); | |
return promise; | |
} | |
// Make the first call | |
fakeNetworkCall('/api/endpoint/1/') | |
// We can call 'then' on the promise that is returned by our function | |
// This allows us to handle the response eventually returned by the fulfilled promise. | |
.then(result => { | |
console.log(result); | |
return fakeNetworkCall('/api/endpoint/2/'); | |
}) | |
// We returned another promise | |
// so I can just make the other call like this! | |
.then(result => { | |
console.log(result); | |
return fakeNetworkCall('/api/endpoint/3/'); | |
}) | |
// And here we go with the third call. | |
// Phew - no need to indent! | |
.then(result => { | |
console.log(result); | |
}) | |
// Handle any errors! | |
.catch(error => { | |
console.log("Error!"); | |
console.log(error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment