A chain promises to process data through a promise-laden gold field.
A simple promise -
|
|
As you have seen earlier the promise gets initialized and next statement (‘promise initialized’) gets executed without waiting to resolve promise.
What if you want to execute something after the promise is resolved? This is where promise chaining comes in.
You can chain the then
statements to tie multiple executions to a single promise.
|
|
The first resolver will receive argument when resolved, show result and return a value. The subsequent then
will again be an implicit promise, execution waits until the end is complete to get to the next then
. This continues until all then
s execute one after the other - each time taking arguments from the previous return
.
Practically this has big applications.
- Wait for response from a third party site, then initiate logic to process the response
- Pass messages across different systems sequentially (but keeping each one of those async to our own program)
- Load scripts sequentially on a web page and do a clean dependency management
I am aware that the first two examples are the same - I breathe integration.
Each of the then
can have their own promises, but you would have to handle them separately. And, good luck to those who maintain them.
Use a catch
statement like normal to process errors for a promise. You can use multiple catch
to catch errors from then
but you would have to explicitly throw
error if you want to stop execution.
|
|
As an important aside, it is always a good idea to manage errors within promises without throwing exceptions at the caller. ‘Fail gracefully rather than making a big mess’ is the motto.