then catch finally javascript code example

Example 1: try catch finally in javascript

try { // Try to run this code
  alert( 'try' ); 
  if (confirm('Make an error?')) BAD_CODE();
} catch (e) { // Code throws error
  alert( 'catch' );
} finally { // Always run this code regardless of error or not
  alert( 'finally' );
}

Example 2: axios fainally

.finally(function() {
   // settled (fulfilled or rejected)
});
.finally(()=> {
   // settled (fulfilled or rejected)
});

Example 3: what is axios .finally on promise

//The finally() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome.

//So if you want to setloading to false regardless of error or success, do this

axios
      .get('/products', { params: params })
      .then((response) => {
        if (isMountedRef.current) {
          setProducts(response.data.data);
          setMeta(response.data.meta);
        }
      })
      .finally(() => {
        setLoading(false);
      });

Example 4: try catch finally in javascript

try {
  alert( 'try' );
  if (confirm('Make an error?')) BAD_CODE();
} catch (e) {
  alert( 'catch' );
} finally {
  alert( 'finally' );
}