8

I have the following:

new Promise(resolve => setTimeout(resolve, 2000))
    .then(() => console.log("after 2 seconds"));

new Promise(resolve => setTimeout(resolve, 3000))
    .then(console.log("before 3 seconds (instantly)"));

which produces the following output:

> node index.js
before 3 seconds (instantly)
after 2 seconds

Promise.then() expects a onFulfilled function, but I passed in console.log("before 2 seconds (instantly)"), which is not a function. Two-part question:

  • Why does console.log("before 2 seconds (instantly)") get executed right away (or at all)?
  • Why didn't the second Promise raise an exception when I didn't pass in a function?
neverendingqs
  • 4,006
  • 3
  • 29
  • 57
  • "Why does console.log("before 2 seconds (instantly)") get executed right away (or at all)?" Why *wouldn't* it get executed instantly? Before the result of an expression can be passed as an argument, it needs to be evaluated. In this case, evaluating `console.log("before 3 seconds (instantly)")` results in stuff being logged to the console, followed by the `undefined` result being used as an argument for invoking `Promise#then`. – Asad Saeeduddin Feb 07 '17 at 16:22
  • 1
    Did [my answer below](http://stackoverflow.com/questions/42094764/why-is-it-possible-to-pass-in-a-non-function-parameter-to-promise-then-without/42094874#42094874) answer your questions? Any comments? – rsp Feb 10 '17 at 11:02

3 Answers3

7

The code

console.log("before 3 seconds (instantly)")

is an expression, specifically a function call expression. Wherever that appears, it means the same thing, including an appearance as an argument to the .then() method of a Promise. As in any other similar language, an expression used in a function call is evaluated before the function call, so

.then(console.log("before 3 seconds (instantly)"))

results in the console.log() function being called first, with the return value then passed to .then(). That's why you see the message in the console immediately.

Passing undefined to .then() is allowed, and since that's what console.log() returns, there's no error raised.

If you want that console.log() to happen when the Promise is fulfilled, you'd wrap it in a function:

.then(function() { console.log("after 3 seconds"); })
Pointy
  • 405,095
  • 59
  • 585
  • 614
4

Why is it possible to pass in a non-function parameter to Promise.then() without causing an error?

Yes. All non-function arguments should be ignored. See below.

Why does console.log("before 2 seconds (instantly)") get executed right away (or at all)?

Because in JS the arguments to functions calls are evaluated instantly (applicative order).

Why didn't the second Promise raise an exception when I didn't pass in a function?

Because console.log returns undefined and .then() with no arguments is legal (because both handlers are optional). In your example console.log() returns undefined so it is like calling .then() with no arguments.

But even if it was called with some arguments that are not functions, they would still get ignored. For example even in this example the 'ok' would still get to the console.log at the end, which may be surprising:

Promise.resolve('ok')
    .then()
    .then(false)
    .then(null)
    .then(1)
    .then('x')
    .then([1, 2, 3])
    .then({a: 1, b: 2})
    .then(console.log);

See the Promises/A+ specification, section 2.2.1 that describe the arguments to the .then() method:

2.2.1 Both onFulfilled and onRejected are optional arguments:

  • If onFulfilled is not a function, it must be ignored.
  • If onRejected is not a function, it must be ignored.
rsp
  • 107,747
  • 29
  • 201
  • 177
2

Why does console.log("before 2 seconds (instantly)") get executed right away (or at all)?

A function's parameters are evaluated before the function is called. When you do alert(1+2) you expect 1+2 to be evaluated first, and when you do alert(console.log("...")) you should likewise expect console.log("...") to be evaluated first. There's nothing special about then; it's just a regular function and its arguments are treated the same as any other function's arguments.

Why didn't the second Promise raise an exception when I didn't pass in a function?

Because console.log returns undefined, and the language specification (ECMAScript 2015) says what should happen when you call then(undefined), and it's not throwing an exception. Let's look at what it does say:

25.4.5.3.1 PerformPromiseThen ( promise, onFulfilled, onRejected, resultCapability )

The abstract operation PerformPromiseThen performs the “then” operation on promise using onFulfilled and onRejected as its settlement actions. The result is resultCapability’s promise.

  1. Assert: IsPromise(promise) is true.
  2. Assert: resultCapability is a PromiseCapability record.
  3. If IsCallable(onFulfilled) is false, then
    1. Let onFulfilled be "Identity".
  4. If IsCallable(onRejected) is false, then
    1. Let onRejected be "Thrower".
  5. Let fulfillReaction be the PromiseReaction { [[Capabilities]]: resultCapability, [[Handler]]: onFulfilled }.
  6. ...

The salient points here are (3) and (5). In (3), since onFulfilled is undefined, IsCallable(onFulfilled) is false and so onFulfilled is set to "Identity". Then, in (5), a PromiseReaction is created with the [[Handler]] onFulfulled, which we know is "Identity".

Here's what the section PromiseReaction Records says about "Identity":

If [[Handler]] is "Identity" it is equivalent to a function that simply returns its first argument.

So there you have it. Calling then(undefined) is basically the same as calling then(a => a), which is why you don't get an error.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182