如何理解这段 Promise 代码?

How to understand this Promise code?

'use strict';

Promise.resolve(() => 'John')
  .then((args) => {
    console.log(args);
    throw new Error('ops')
  })
  .catch((ex) => {
    console.log(ex)
  })
  .then(() => {
    throw new Error('ups')
    console.log('Doe')
  })

我认为console.log(args);应该输出'John',但是当我运行这段代码时,输​​出是[ [Function] ]

所以我很困惑。

Promise.resolve 将使用您传递给它的值创建一个新的 Promise。所以,在你的情况下,你的承诺实际上是用函数对象解决的。这意味着,then 处理程序被传递给函数对象本身。

你应该做的是

new Promise((resolve, reject) => resolve('John'))
  .then(args => {
    console.log(args);
    throw new Error('ops')
  })
  .catch(console.log.bind(console));

现在,您正在创建一个 Promise 对象并使用值 John 解析它。


如果你希望你的 Promise 很容易被解析为一个值,那么不要传递函数对象,而是将实际值本身传递给 Promise.resolve 函数。

Promise.resolve('John')
  .then(args => {
    console.log(args);
    throw new Error('ops')
  })
  .catch(console.log.bind(console));

现在,您有一个 Promise,解析值为 Johnthen 处理程序将获得解析值 John

注意: 当您知道实际的解决方法时,这是推荐的创建 Promise 的方法,这样您就可以避免 Promise constructor anti-pattern

resolve 用于将参数直接传递给 then-handler

如果你想要'John',你需要在调用resolve()时调用匿名函数

Promise.resolve(function(){return 'John';}());

注意 }() 函数调用。

'use strict';

Promise.resolve('John')
  .then((args) => {
    console.log(args);
    throw new Error('ops')
  })
  .catch((ex) => {
    console.log(ex)
  })
  .then(() => {
    throw new Error('ups')
    console.log('Doe')
  })

我修改了Promise.resolve('John'),成功了。 请参阅 Promise.resolve.