First off, the first return is returning the result of getUsers().then()
from your getFirstUser()
function. So, the return value from getFirstUser()
is a promise.
The second return is returning a value from the .then()
promise callback. In the world of promises, returning a value from a .then()
handler sets the resolved value of that promise to that value.
The second return is NOT returning from the getFirstUser()
function. It's returning only from the .then()
callback function and that return value goes back into the promise infrastructure that called the .then()
handler.
Timing-wise, it's also useful to understand what happens in a timeline. Here's a step-by-step description:
- Someone calls
getFirstUser().then(somefn)
.
- As
getFirstUser()
executes, it calls getUsers()
. That function initiates some asynchronous operation (perhaps a database query operation) and then returns a promise (I will call p1
). The database operation has not yet completed.
- Then, on that returned promise
.then(fn)
is executed. This just registers the function as a .then()
callback and it returns a new promise. The .then()
handler is not yet called, it is stored to be called later.
.then()
returns a new promise (I will call p2
).
- Then the function
getFirstUser()
is done and it returns the p2
promise from the previous step.
- Then, sometime later, the
getUsers()
promise resolves and causes the .then()
handler that was previously registered on it to get called.
- When that
.then()
handler gets called, your return users[0].name;
executes and returns that value into the promise infrastructure. That value becomes the resolved value of promise p2
which is the promise that was returned from getFirstUser()
.
- Promise
p2
is now resolved. This causes the original caller's .then()
handler to be called (the one in step #1) and someFn
is called and passed the first user resolved value.