Solution to https://twitter.com/nolanlawson/status/578948854411878400.
doSomething().then(function () {
return doSomethingElse();
}).then(finalHandler);
Answer:
doSomething
|-----------------|
doSomethingElse(undefined)
|------------------|
finalHandler(resultOfDoSomethingElse)
|------------------|
doSomething().then(function () {
doSomethingElse();
}).then(finalHandler);
Answer:
doSomething
|-----------------|
doSomethingElse(undefined)
|------------------|
finalHandler(undefined)
|------------------|
doSomething().then(doSomethingElse())
.then(finalHandler);
Answer:
doSomething
|-----------------|
doSomethingElse(undefined)
|---------------------------------|
finalHandler(resultOfDoSomething)
|------------------|
doSomething().then(doSomethingElse)
.then(finalHandler);
Answer:
doSomething
|-----------------|
doSomethingElse(resultOfDoSomething)
|------------------|
finalHandler(resultOfDoSomethingElse)
|------------------|
Understanding these puzzles correctly requires an assumption that doSomething() and doSomethingElse() return promises. @scottnonnenberg is correct that if doSomethingElse() returned a function then the results listed for puzzle #4 would be expected for #3. Since doSomethingElse() returns a promise and not a function that returns a promise, however, the then() function treats the promise parameter as a null and the value therefore falls through to the finalHandler. This threw me as well given I arrived at this gist prior to reading the associated blog article: https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html.