Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Last active July 26, 2022 08:02
Show Gist options
  • Save nolanlawson/940d1a390b2d9cf9483c to your computer and use it in GitHub Desktop.
Save nolanlawson/940d1a390b2d9cf9483c to your computer and use it in GitHub Desktop.
Promises puzzle cheat sheet

Promises puzzle answer sheet

Solution to https://twitter.com/nolanlawson/status/578948854411878400.

Puzzle #1

doSomething().then(function () {
  return doSomethingElse();
}).then(finalHandler);

Answer:

doSomething
|-----------------|
                  doSomethingElse(undefined)
                  |------------------|
                                     finalHandler(resultOfDoSomethingElse)
                                     |------------------|

Puzzle #2

doSomething().then(function () {
  doSomethingElse();
}).then(finalHandler);

Answer:

doSomething
|-----------------|
                  doSomethingElse(undefined)
                  |------------------|
                  finalHandler(undefined)
                  |------------------|

Puzzle #3

doSomething().then(doSomethingElse())
  .then(finalHandler);

Answer:

doSomething
|-----------------|
doSomethingElse(undefined)
|---------------------------------|
                  finalHandler(resultOfDoSomething)
                  |------------------|

Puzzle #4

doSomething().then(doSomethingElse)
  .then(finalHandler);

Answer:

doSomething
|-----------------|
                  doSomethingElse(resultOfDoSomething)
                  |------------------|
                                     finalHandler(resultOfDoSomethingElse)
                                     |------------------|
@derekgreer
Copy link

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.

@anfedorov
Copy link

it's called doSomething not doSomethingAndReturnPromise. duuuh!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment