Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

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

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"); })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...