为什么可以将非函数参数传递给 Promise.then() 而不会导致错误? [英] Why is it possible to pass in a non-function parameter to Promise.then() without causing an error?

查看:26
本文介绍了为什么可以将非函数参数传递给 Promise.then() 而不会导致错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:

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("before 2 seconds (instantly)"),它不是一个函数.两部分问题:

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("before 2 seconds (instantly)") 立即(或根本)执行?
  • 当我没有传入函数时,为什么第二个 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() 函数被首先调用,然后将返回值传递给 .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 传递给 .then() 是允许的,因为这是 console.log() 返回的内容,所以不会引发错误.

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

如果您希望 console.log() 在 Promise 完成时发生,您可以将它包装在一个函数中:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆