简体   繁体   English

如何理解这个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')
  })

I think console.log(args); 我认为console.log(args); should output 'John' , but when I run this code, the output is [ [Function] ] 应该输出'John' ,但是当我运行这段代码时,输​​出是[ [Function] ]

So I am confused. 所以我很困惑。

Promise.resolve will create a new Promise resolved with the value you pass to it. Promise.resolve将使用您传递给它的值创建一个新的Promise。 So, in your case, your promise is actually resolved with the function object. 因此,在您的情况下,您的承诺实际上是通过函数对象解决的。 It means that, the then handler is passed the function object itself. 这意味着, then处理程序将传递给函数对象本身。

What you should have done is 你应该做的是

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

Now, you are creating a Promise object and you are resolving that with the value John . 现在,您正在创建一个Promise对象,并且您正在使用值John解析它。


If you want your Promise to be resolved with a value readily, then don't pass the function object but pass the actual value itself to Promise.resolve function. 如果你希望你的Promise很容易被一个值解析,那么不要传递函数对象,而是将实际值本身传递给Promise.resolve函数。

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

Now, you have a Promise, resolved with value John and the then handler will get the resolved value John . 现在,你有一个Promise,用值John解析, then处理程序将获得已解析的值John

Note: This is the recommended way of creating a Promise when you know the actual way to resolve with readily, so that you can avoid the Promise constructor anti-pattern . 注意:当您知道实际解决方法时,这是创建Promise的推荐方法,这样您就可以避免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')
  })

I modify Promise.resolve('John') , it works. 我修改了Promise.resolve('John') ,它有效。 Please see the Promise.resolve . 请参阅Promise.resolve

resolve is used to pass the arguments directly to the then-handler resolve用于将参数直接传递给then-handler

if you want 'John', you need to call the anonymous function in your call to resolve() 如果你想要'John',你需要在你的调用中调用匿名函数来解析()

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

notice the }() function call. 注意}()函数调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM