In the following code block only 'first promise' is logged to console. Why is that? I was trying to write a test to figure out how .then()'s execute after .catch() but was surprised when nothing besides the first promise ran. Whats going on here?
function foo() {
return new Promise((resolve, reject) => {
return console.log('first promise')
})
.then(() => console.log('first then'))
.catch(() => console.log('catch block'))
.then(() => console.log('last block'))
.then(() => resolve)
}
foo();
Without Executing If you find yourself wanting a "cold" promise in the sense that your promise doesn't execute until you await on it, you should just use an async function. Calling an async function returns a new promise every time.
The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
The reject function of a Promise executor changes the state of the Promise , but does not stop the executor. In general, it is recommended to add a return statement after the reject to stop unintended code execution.
A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.
As Yury said, you're not resolving the promise, simply returning a log.
https://jsfiddle.net/k7gL57t3/
function foo() {
var p1 = new Promise((resolve, reject) => {
resolve("Test");
})
p1.then(() => console.log('first then'))
.then(() => console.log('last block'))
.then(() => resolve)
.catch(() => console.log('catch block'));
}
foo();
I believe it's because your then
chain does not have closure to resolve
inside of the Promise callback. Try this:
function foo() {
return Promise.resolve()
.then(() => console.log('first then'))
.catch(() => console.log('catch block'))
.then(() => console.log('last block'));
}
or this if you want to use the Promise constructor:
function foo() {
return new Promise((resolve, reject) => {
console.log('first promise');
return resolve();
})
.then(() => console.log('first then'))
.catch(() => console.log('catch block'))
.then(() => console.log('last block'));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With