I'm trying to wrap my mind around promises in JavaScript. I was under the illusion that once a Promise was resolved it could never go back to rejected. To test that I wrote a little script. I see that the first messages that come back are the resolve messages "1 resolve 2" etc. I expected the first message to be "0 reject 1".
for (let i = 0; i < 10; i++) {
let p = new Promise((resolve, reject) => {
let a = 1 + (i % 2)
if (a === 2) {
resolve(i + ' resolve ' + a)
} else {
reject(i + ' reject ' + a)
}
})
p.then((message) => {
console.log(message)
}).catch((message) => {
console.log(message)
})
}
at the console:
[Log] 1 resolve 2
[Log] 3 resolve 2
[Log] 5 resolve 2
[Log] 7 resolve 2
[Log] 9 resolve 2
[Log] 0 reject 1
[Log] 2 reject 1
[Log] 4 reject 1
[Log] 6 reject 1
[Log] 8 reject 1
< Promise {status: "pending"}
thanks for you help....
After reading
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
I got to this code. The catch is removed.
for (let i = 0; i < 10; i++) {
let p = new Promise((resolve, reject) => {
let a = 1 + (i % 2)
if (a === 2) {
resolve(i + ' resolve ' + a)
} else {
reject(i + ' reject ' + a)
}
})
p.then((message) => {
console.log(message)
}, failed => {
console.log(failed)
})
}
at the console:
[Log] 0 reject 1
[Log] 1 resolve 2
[Log] 2 reject 1
[Log] 3 resolve 2
[Log] 4 reject 1
[Log] 5 resolve 2
[Log] 6 reject 1
[Log] 7 resolve 2
[Log] 8 reject 1
[Log] 9 resolve 2
< Promise {status: "pending"}
You can see what's going on under the hood by using your the console of your browser's dev tools and, possibly, setting break points (this articles might be helpful if u're using Chrome or Firefox):
As you can see, all your 10 promises are created before any of them are executed (resolve/reject).
Interestingly, in your code the resolved promises are handled first.
If you define the handlers in two separate definitions, you'll get the expected results:
p.then((message) => {
console.log(message)
})
p.catch((message) => {
console.log(message)
})
Output:
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