Skip to content Skip to sidebar Skip to footer

Using Kris Kowal's Q. How Should I Catch If Any Errors Have Been Thrown Throughout The Life Of A Chained Promise?

I'm new to promises, and I just started using Kris Kowal's Q today (I've read about it before and used it a little with Angular.js), and I was doing an Ajax call with jQuery and tu

Solution 1:

A handled rejection is like a caught exception. It stops propagating since well, it was handled. If you want to handle the rejection and keep it rejected you need to rethrow, again, just like in synchronous code.

try {
       thrownewError();
    } catch(e){
        // handle error   
    }
    // no error here this code will keep running.

If you want it to keep rejecting and handle it, you need to rethrow:

try {
       thrownewError();
    } catch(e){
        // handle error   throw e;
    }
    // this code will not run

The same with promises, just like you wrote. This is not particularly odd about promises, this is how synchronous exceptions work as well. If you want to propagate - you re-throw, otherwise - the errors are considered handled.

Solution 2:

If you don't throw in fail it means you recover from error to success (see: Rejection into success [use cursors] mind fail is alias for catch), so result promise ends as successful. It can't be other way

Instead of using fail see if Q provides function which provides access to result and returns self promise (something like aside in implementation I mantain).

Also your flow can be simpler with less then's, see:

function deleteEvent(id) {
    return Q($.ajax({
        ....
    })).then(function (data) { // success// on successUpdateDOMforEventsChanged();
    }); // No need for error handler
};

deleteEvent(event._id).done(function () { // AJAX call was a success delete the things
    $('#calendar').fullCalendar('removeEvents', event._id);
}, , function (e) { // It failed somewhere alert the user.
    console.error(e.stack || e.message);
    alert("There was an error with deleting the event. Check your network connection and try again.")
});

Post a Comment for "Using Kris Kowal's Q. How Should I Catch If Any Errors Have Been Thrown Throughout The Life Of A Chained Promise?"