Promises
Promises came about as a response to the callback hell problem described in the previous section. They have quite a long history, stretching back to the early 80s, when the legendary Barbara Liskov coined the term Promise
. The idea of a Promise
is to flatten out async code. A promise is said to have the following states:
- Pending: This means it has not yet been decided or that the data is not available yet
- Fulfilled: The data has come back
- Rejected: An error happened during the operation
Thenables
Something important to know is that a Promise
returns straight away, but the result is not available straight away. Promises are also known as thenables, because you need to register a callback with its then()
method once the data has been received, like so:
const promise = new Promise((resolve, reject) => { // either call resolve() if we have a success or reject() if it fails }); // the 'promise' variable points to a construct // that will eventually contain a value promise((data) ...