Reputation: 10252
'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.
Upvotes: 6
Views: 79
Reputation: 239653
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.
Upvotes: 4
Reputation: 10252
'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.
Upvotes: 3
Reputation: 10877
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.
Upvotes: 1