This is how I understand the promise syntax to work:
promise.then((value) => {
// handle async return
}, (error) => {
console.log(error);
});
The promise can be fulfilled or rejected and you declare two closures separated by a comma where the first one handles success and the second handles failure. But all or most of the code I see doesn't use this syntax; it uses catch.
promise.then((value) => {
// handle async return
}).catch((error) => {
console.log(error);
});
However, I've read that catch()
itself creates a new promise. Is that true? Because, as far as I understand it, catch is supposed to be the final stop of a process when an error is thrown, or does it work differently in JavaScript?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
YES.
p1.then(function(value) {
console.log(value); // "Success!"
throw new Error('oh, no!');
}).catch(function(e) {
console.error(e.message); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
The return value of catch is thenable.