A typical program cycle may consists of multiple operations that needs to be run in the background to achieve the ultimate objective of the program. For an example when you are trying to watch a YouTube video using your web browser, certain amount of the video file will be read and added to your browser cache and while you are playing the video, browser program will fetch the next part of the video in the back-end which allows you to watch the video uninterrupted.
The processes that happened in the backed-end are call as Asynchronous operations This article is not about Asynchronous calls instead we are going to look at how to use Promises to make a call to external programs that may delay the response but we are not going to hold our program due to this delay.
A promise: is a wrapper object that can be used as a placeholder to make a call to a program that may take some time to execute such as reading from a external API, writing to disk etc. We can use this place holder to define what needs to be done once operation is completed or failed.
Below example code snipped shows a function wrapped inside a promise which can be either the fulfilled or rejected.
- A promise can either be resolved or rejected. Not both.
- There are situations you may have to connect few operations together based on the outcome. : promise chaining.
- There are situations you may be calling multiple promises but you want to get the 1st one that was resolved. : promise raise.
- You are calling multiples asynchronous calls and you need to make sure all the calls are either rejected or resolved. : promise all.