Created
April 11, 2018 04:40
-
-
Save deconstructionalism/0e8f8f44ba4cba5d30d3b0ef34150ec4 to your computer and use it in GitHub Desktop.
Example of a simple promise and wrapping subsequent async function calls automatically in a promise
This file contains hidden or 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
| const makeAPromise = () => { | |
| return new Promise( (resolve, reject) => { | |
| const statusCodes = [200, 400] | |
| // simulation of an async AJAX request | |
| setTimeout(() => { | |
| // pick a random status after 3 s | |
| const status = statusCodes[Math.floor(Math.random() * statusCodes.length)] | |
| if (status == 200) { | |
| resolve(status) | |
| } | |
| if (status == 400) { | |
| reject(status) | |
| } | |
| }, 3000) | |
| }) | |
| } | |
| const myOtherAsyncThing = () => { | |
| setTimeout(() => { | |
| console.log('yay') | |
| }, 1500) | |
| } | |
| makeAPromise().then(res => console.log(`Your request worked fine and got a ${res} code`)) | |
| .then(myOtherAsyncThing) | |
| .catch(err => console.error(`Hey, your request crapped out with a ${err} code`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment