为什么可以将非函数参数传递给Promise.then()而不会导致错误? [英] Why is it possible to pass in a non-function parameter to Promise.then() without causing an error?
问题描述
我有以下内容:
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)"));
产生以下输出:
> node index.js
before 3 seconds (instantly)
after 2 seconds
Promise.then()预计一个 onFulfilled
函数,但我传入 console.log(在2秒之前(立即))
,这是不是一个功能。由两部分组成的问题:
Promise.then() expects a onFulfilled
function, but I passed in console.log("before 2 seconds (instantly)")
, which is not a function. Two-part question:
- 为什么
console.log(在2秒之前(立即))
立即执行(或根本不执行)? - 当我没有传递函数时,为什么第二个Promise没有引发异常?
- 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?
推荐答案
代码
console.log("before 3 seconds (instantly)")
是表达式,特别是一个函数调用表达式。无论出现在哪里,它都意味着相同的东西,包括外观作为Promise的 .then()
方法的参数。与任何其他类似语言一样,函数调用中使用的表达式在函数调用之前进行评估,因此
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)"))
结果在 console.log()
函数中调用 first ,然后将返回值传递给 .then()
。这就是你立即在控制台中看到消息的原因。
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.
将 undefined
传递给。然后()
是允许的,因为那是 console.log()
返回的,所以没有引发错误。
Passing undefined
to .then()
is allowed, and since that's what console.log()
returns, there's no error raised.
如果你希望在实现Promise时发生 console.log()
,你可以将它包装在一个函数中:
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"); })
这篇关于为什么可以将非函数参数传递给Promise.then()而不会导致错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!