These are some simple examples for JavaScript’s Promise object. Use it to make your asynchronous operations code more managable and avoid callback hells.
Basic Example
In this example, we want to run something after an async task. Using the Promise syntax, the code seems to flow the async operation into a more synchronous style. At least that is how I see and value it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Chaining – Multiple Async Tasks in Sequence
Sometimes it is useful to run multiple async task in sequence. Let’s say we need to:
- Perform an AJAX call to get userId from the server.
- With the userId, perform another AJAX call to retrieve products for the user.
- Render the products on screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
Fork/Join
Another common pattern is to have multiple tasks start as soon as they can. As soon as all the tasks complete, we execute some code. The difference between this and chaining above is all the promises run at the same time instead of running one by one in sequence.
A scenario for this could look like:
- Get current weather from server.
- Get user profile from server.
- Get latest news from a server.
- Render data from the three tasks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
Details
Hopefully these examples make it easier to get started with JavaScript promises. It is still useful to refer to Promise documentation on other features like error handling and Promise.race().
Note that all the examples can executed on your browser’s developer console – provided the browser supports Promise (Chrome >= 32; Firefox >= 29; IE >= 11; Opera >= 19; Safari >= 7.1).