如何理解这个承诺代码

How to understand this Promise code?

本文关键字:承诺 代码 何理解      更新时间:2023-09-26
'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将创建一个新的承诺,使用您传递给它的值进行解析。因此,在您的情况下,您的承诺实际上是通过函数对象解决的。这意味着,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,使用值 John 解析,then处理程序将获得解析的值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'),它有效。请参阅承诺.解析。

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

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

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

请注意}()函数调用。