Search code examples
javascriptpromisebreakout

How to break out of a promise (.then) statement javascript


I'm having a problem trying to break out of a promise statement when an error occurs in a catch statement.

I'm not sure if I can throw an error inside a catch statement.

The problem: The catch function isn't doing anything when I throw an error.

Expected result: For the catch statement to display an alert and break the promise chain.

The code:

        if (IsEmail(email)) {
        $('body').loadingModal({
              position: 'auto',
              text: 'Signing you in, please wait...',
              color: '#fff',
              opacity: '0.9',
              backgroundColor: 'rgb(0,0,0)',
              animation: 'doubleBounce'
        });

        var delay = function(ms){ return new Promise(function(r) { setTimeout(r, ms) }) };
        var time = 2000;

        delay(time)
        .then(function() { $('body').loadingModal('animation', 'foldingCube'); return delay(time); } )
        .then(function() { 
            firebase.auth().signInWithEmailAndPassword(email, password)
            .then(function () {
                var user = firebase.auth().currentUser;
                uid = user.uid;
                configure();
            })
            .catch(function(error) {
                throw error;
            });
        })
        .then(function() { $('body').loadingModal('color', 'white').loadingModal('text', 'Welcome to Dtt deliveries').loadingModal('backgroundColor', 'orange');  return delay(time); } )
        .then(function() { $('body').loadingModal('hide'); return delay(time); } )
        .then(function() { $('body').loadingModal('destroy') ;} )
        .catch(function(error) {
            alert("Database error: " + error);
        }); 
    }
    else {
        alert("Please enter a valid email");
        return;
    }

Solution

  • The second .then after the delay resolves immediately, because nothing is being returned from it. Return the signInWithEmailAndPassword call instead, because it returns a Promise that you need to chain together with the outer Promise chain:

    .then(function() {
      return firebase.auth().signInWithEmailAndPassword(email, password)
      // ...
    

    Also, catching and immediately throwing doesn't really do anything - unless you need to handle an error particular to signInWithEmailAndPassword there, feel free to omit that catch entirely:

    delay(time)
      .then(function() { $('body').loadingModal('animation', 'foldingCube'); return delay(time); } )
      .then(function() { 
        return firebase.auth().signInWithEmailAndPassword(email, password)
      })
      .then(function () {
        var user = firebase.auth().currentUser;
        uid = user.uid;
        configure(); // if configure returns a Promise, return this call from the `.then`
      })
      .then(
      // ...
      .catch(function(error) {
        alert("Database error: " + error);
      });
    

    If configure returns a Promise as well, then you need to return it too. (if it's synchronous, there's no need)

    (you might also consider using a more user-friendly way of displaying the error, perhaps use a proper modal instead of alert)

    Another option to consider is using await instead of all these .thens, the control flow may be clearer:

    (async () => {
      if (!IsEmail(email)) {
        alert("Please enter a valid email");
        return;
      }
      $('body').loadingModal({
        position: 'auto',
        text: 'Signing you in, please wait...',
        color: '#fff',
        opacity: '0.9',
        backgroundColor: 'rgb(0,0,0)',
        animation: 'doubleBounce'
      });
    
      var delay = function(ms) {
        return new Promise(function(r) {
          setTimeout(r, ms)
        })
      };
      var time = 2000;
    
      try {
        await delay(time);
        $('body').loadingModal('animation', 'foldingCube');
        await delay(time);
        await firebase.auth().signInWithEmailAndPassword(email, password)
        var user = firebase.auth().currentUser;
        uid = user.uid;
        configure(); // if this returns a Promise, `await` it
        $('body').loadingModal('color', 'white').loadingModal('text', 'Welcome to Dtt deliveries').loadingModal('backgroundColor', 'orange');
        await delay(time);
        $('body').loadingModal('hide');
        await delay(time);
        $('body').loadingModal('destroy');
      } catch(error) {
        alert("Database error: " + error);
      }
    })();