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,
then
is called if no errors occurred,catch
is called otherwise, andfinally
is 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
catch
is not defined,then
is always called.finally
is 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
then
is not defined,catch
is still only called when an error occurs. As always,finally
is 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.