Last active
October 15, 2018 18:38
-
-
Save lei-clearsky/b481617dc3ba814955ef006fd2ce26a4 to your computer and use it in GitHub Desktop.
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
| class PromiseSimple { | |
| } | |
| fakeApiBackend = () => { | |
| const user = { | |
| username: 'John Doe', | |
| favoriteNumber: 42, | |
| profile: 'https://gitconnected.com/johndoe' | |
| }; | |
| // Introduce a randomizer to simulate the the probability of encountering an error | |
| if (Math.random() > .05) { | |
| return { | |
| data: user, | |
| statusCode: 200, | |
| }; | |
| } else { | |
| const error = { | |
| statusCode: 404, | |
| message: 'Could not find user', | |
| error: 'Not Found', | |
| }; | |
| return error; | |
| } | |
| }; | |
| // Assume this is your AJAX library. Almost all newer ones return a Promise Object | |
| const makeApiCall = () => { | |
| return new PromiseSimple((resolve, reject) => { | |
| setTimeout(() => { | |
| const apiResponse = fakeApiBackend(); | |
| if (apiResponse.statusCode >= 400) { | |
| reject(apiResponse); | |
| } else { | |
| resolve(apiResponse.data); | |
| } | |
| }, 5000); | |
| }); | |
| }; | |
| makeApiCall() | |
| .then((user) => { | |
| console.log('In the first .then()'); | |
| return user; | |
| }) | |
| .then((user) => { | |
| console.log(`User ${user.username}'s favorite number is ${user.favoriteNumber}`); | |
| return user; | |
| }) | |
| .then((user) => { | |
| console.log('The previous .then() told you the favoriteNumber') | |
| return user.profile; | |
| }) | |
| .then((profile) => { | |
| console.log(`The profile URL is ${profile}`); | |
| }) | |
| .then(() => { | |
| console.log('This is the last then()'); | |
| }) | |
| .catch((error) => { | |
| console.log(error.message); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment