The other day I was working with three asynchronous functions e.g. asyncF1, asyncF2, asyncF3 where each one returns a Promise to the next one. I had a basic understanding of Promises so I started coding and got some code like this
This code shows what they call a “Callback Hell”. Fortunately Promises have techniques allow you to avoid long or, I would say, nesting at all.
I think the main Promise magic happens when a result of the
becomes a new Promise. This means you can call a chain of
.then() methods and pass parameters between them.
- If you return a simple value, the next Promise is resolved with that value
If you return a Promise, the next
.then()waits for it to be resolved/rejected and is called with the corresponding result
There can be one or more
.then() method calls that do not have an error handler, then the error is passed to the closest
If there is a
.catch() inside a chain of
.then() calls, the returned value from
.catch() is passed to the next
.catch(). So this can be used to set a fallback or a default value
That is the basic info you should know while working with Promises chaining. I hope this helps you.