Promise.prototype.finally
devoted to the Promise.prototype.finally method . According to the caniuse.com resource, the support level of this method is approximately 81%. This method can also be used in the Node.js environment.finally
promis method is one of the most important innovations of the standard, which allows you to set a function that will be executed regardless of the result of promis. This function will be performed with the successful resolution of promis and with its rejection. const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve('success!!!'); }, 2000); });
then
block: myPromise.then( result => { console.log(result) }, failMessage => { console.log(failMessage) } );
then
method is passed two anonymous functions. The first will be executed if the promise is successfully resolved. The second is when it is rejected. Our promise always completes successfully, the message success!!!
will always be displayed success!!!
. All this is very good, but what if you need to, so that certain actions would be performed after the rejection of the promise, and after the successful completion of its work? The finally
method will help us here: const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve('success!!!'); }, 2000); }); myPromise.then( result => { console.log(result) }, failMessage => { console.log(failMessage) } ).finally(finallyMessage => { console.log('FINALLY!!')});
FINALLY!!
, which tells us that the callback function passed to the finally
method works anyway. In order to verify this - you can experiment .Promise.prototype.finally
be useful? For example - if at the launch of the promise used to load something, some animation starts to play, in finally
you can complete this animation. In the finally
block, you can, for example, close a certain modal window. In fact, there are many situations in which the finally
method can be useful.Source: https://habr.com/ru/post/427405/
All Articles