简体   繁体   中英

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); should output 'John' , but when I run this code, the output is [ [Function] ]

So I am confused.

Promise.resolve will create a new Promise resolved with the value you pass to it. 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.

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 .


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.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 .

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 .

'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. Please see the Promise.resolve .

resolve is used to pass the arguments directly to the then-handler

if you want 'John', you need to call the anonymous function in your call to resolve()

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

notice the }() function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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