Promises
ES6 introduces promises as an alternate to callbacks. Like callbacks, promises are used to retrieve the results of an asynchronous function call. Using promises is easier than callbacks and produces more readable code. However, to implement promises for your asynchronous functions requires more work.
A promise object represents a value that may be available now or in the future, or possibly never. As the name suggests, a promise may be fulfilled or rejected. A promise acts as a placeholder for the eventual result.
A promise has three mutually exclusive states, which are as follows:
- A promise is pending before the result is ready; this is the initial state.
- A promise is fulfilled when the result is ready.
- On an error, a promise is rejected.
When a pending promise is either fulfilled or rejected, associated callbacks/handlers that are queued up by the then()
method of the promise are executed.
The purpose of promises is to provide a better syntax for the CPS callbacks. The typical CPS style...