I really enjoy using JavaScript Promises for asynchronous operations. I find the API to be clear and easy to understand. Example:
dispatchAsyncProcess()
.then(response => {
// Success callback 🎉
})
.catch(error => {
// Error callback 😟
})
.finally(() => {
//release resources / Stop loader etc 🛑
});
Life is not always so straight forward though! Chances are, we do not always need all the available callbacks. So what are the rules around which callbacks are executed and when?
The gist
-
Promises have 3 possible callbacks, namely:
then,catch, andfinally. -
Each callback itself returns a Promise.
-
The callbacks are executed with the following rules:
-
When all three are defined,
thenis called if no errors occurred,catchis called otherwise, andfinallyis called last:// SCENARIO 1: process is successful dispatchAsyncProcess() .then(response => { // Called }) .catch(error => { // Not called }) .finally(() => { // Called after then }); // SCENARIO 2: process failed dispatchAsyncProcess() .then(response => { // Not Called }) .catch(error => { // Called }) .finally(() => { // Called after catch }); -
If
catchis not defined,thenis always called.finallyis called last:// SCENARIO 3: process is successful dispatchAsyncProcess() .then(response => { // Called }) .finally(() => { // Called after then }); // SCENARIO 4: process failed dispatchAsyncProcess() .then(response => { // Called }) .finally(() => { // Called after then }); -
If
thenis not defined,catchis still only called when an error occurs. As always,finallyis called last:// SCENARIO 5: process is successful dispatchAsyncProcess() .catch(response => { // Not Called }) .finally(() => { // Called }); // SCENARIO 6: process failed dispatchAsyncProcess() .catch(response => { // Called }) .finally(() => { // Called after catch });
-
Armed with this knowledge, we can confidently work with promises in our code.