Ad

How To Understand This Promise Code?

- 1 answer

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

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad