Promises
Promises are built-in ES6.
Promises vs Callbacks
For HTTP Requests, our existing solution is to use callbacks:
A few problems exist with callbacks. One is known as "Callback Hell". A larger problem is decomposition.
The callback pattern requires us to specify the task and the callback at the same time. In contrast, promises allow us to specify and dispatch the request in one place:
and then to add the callback later, and in a different place:
This also allows us to attach multiple handlers to the same task:
More on Promises
.then()
always returns a promise. Always.
p2
is now a promise regardless of what transformData()
returned. Even if something fails.
If the callback function returns a value, the promise resolves to that value:
p2
will resolve to “1”.
If the callback function returns a promise, the promise resolves to a functionally equivalent promise:
p2
is now functionally equivalent to newPromise.
p2
is still a promise, but now it will be rejected with the thrown error.
Why won't the second callback ever be called?
Catching Rejections
The function passed to then
takes a second argument, i.e. error
, which represents error catching within the promise chain.
Note that one catch at the end is often enough.
Last updated
Was this helpful?