Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Did you ask yourself, "What is the result of the
then method?" Here is the answer: It's a promise. But what promise is it? It can be the promise you want. It's easier to explain with an example so take a look at the following code and run it.
First of all, when dealing with promises chains, people often put a new line before the first call. It's pretty hard to read and confusing when you don't know the syntax. Read the code carefully. The statement starting on line 3 ends on line 17. Each call of
then is part of the same "line of code".
So, what is going on here? Let's take a deep breath and analyze it line by line:
- Line 1: We call
job1and we store the returned promise in a variable called
- Line 5: We call
thenon this promise and we attach a callback for when the promise is resolved
- Line 6: We print
data1and it is obvioulsy
result of job 1(see line 22)
- Line 7: On this line, we call
job2and we return the resulting promise. Keep that in mind and go to line 10.
- Line 10: We call
thenon the result of the first
then. The result of
thenis always a promise. Always. At worst, it can be a never resolved promise, but it is a promise. In this case, the promise is the return value of
job2(called at line 7). When you are in a
thencallback, if you return a promise, it will be the resulting promise of the
- Line 11: We print
data2. According to the
resolvecall in the promise returned by
job2(called at line 7),
result of job 2(see line 30). By chaining our 2 promises (
job2is always executed after
job1. Line 6 is executed when the
job1promise is resolved, line 11 is executed when the
job2promise is resolved.
- Line 12: We return a simple string
- Line 15: We call
thenon the result of the
thencall on line 10. The promise here is an auto-resolved promise, and it will pass
'Hello world'in the data. When you are in a
thencallback, if you return anything but a promise, an auto-resolved promise is created, and this promise will be the result of the
- Line 16: We print
data3and this is the
'Hello world'returned at line 12.
- Line 17: End of line 3 (yes, this is a very long line!). At this point, you can add a
thencall if you want.
thenalways returns a promise. And if you decide to return nothing (like at line 16, we don't return anything),
thenreturns an auto-resolved promise with no data (if you try to get any data, you'll get
Chaining promises is very powerfull and simple to use. This is how you master asynchronous code.