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?
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?
-
"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 theundefined
result being used as an argument for invokingPromise#then
. – user1726343 Commented Feb 7, 2017 at 16:22 - 1 Did my answer below answer your questions? Any ments? – rsp Commented Feb 10, 2017 at 11:02
3 Answers
Reset to default 7The 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"); })
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.
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.
- Assert: IsPromise(promise) is true.
- Assert: resultCapability is a PromiseCapability record.
- If IsCallable(onFulfilled) is false, then
- Let onFulfilled be
"Identity"
.- If IsCallable(onRejected) is false, then
- Let onRejected be
"Thrower"
.- Let fulfillReaction be the PromiseReaction { [[Capabilities]]: resultCapability, [[Handler]]: onFulfilled }.
- ...
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.