Why is doSomethingElse() in puzzle 1 undefined ? In my opinion, it should have resultOfDoSomething as in the 4th puzzle.
Nope. resultOfDoSomething is passed to the callback that then was called with, but we just ignore it in the first code:
doSomething().then(function(resultOfDoSomething) { // it here: ^^^^^^^^^^^^^^^^^^^ return doSomethingElse( ); // but not there: ^^ - Ooops! });
What is the difference between 3rd and 4th puzzles? In the third puzzle, in the first we write doSomethingElse() , and in the 4th puzzle we write here only the function name, doSomethingElse . How is this possible? What does doSomethingElse really do inside the fourth puzzle?
As you probably know, this is the difference between the called function and the function itself.
In addition, we always want to - no: must - pass the callback function to then(…) . The following two equivalents:
promise.then(function callback(res) { … });
function callback(res) { … } promise.then(callback);
Expected - you pass the function to the call, so it is tied to the promise, as usual. But callback() (with a call) is no longer a function:
Why doSomethingElse() function run in 3rd puzzle at the same moment as doSomething ?
Because it is called immediately in the then(doSomethingElse()) - it is actually called before then , to which it is an argument. Therefore, in fact, this is called the moment after doSomething() , but at the same turn of the event loop; and two asynchronous events will be executed in parallel.
In addition, then only accepts function arguments, everything else is ignored. So there’s no chain here, it's the same as doing
var promise = doSomething(); doSomethingElse(); promise.then(finalHandler);
Not what we want!
Btw, they are also explained as “Advanced error No. 3: promises against factory promises” and “Advanced error No. 5: promises fail”, which I will consider as a rookie error :-)