网站搜索

javascript - 如何理解这段 Promise 代码?


'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] ]

所以我很困惑。

答案#1

Promise.resolve 会创建一个新的 Promise,并用你传给它的值来解决它。因此,在你的情况下,你的 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,其值为 John 已被解决,并且 then 处理程序将获得已解决的值 John。

注意: 当你已经知道如何立即解决 Promise 时,这是创建 Promise 的推荐方式,这样可以避免使用 Promise 构造函数的反模式。

答案#2

'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。