Skip to content Skip to sidebar Skip to footer

Rejecting Inner Promise After Initial Promise Has Succeeded?

I have a function which issues two async requests before yielding some data. The caller of the method does not need to know about its implementation details. All the caller needs

Solution 1:

Since your code looks a little like pseudo-code (unanswered questions in it for me), the best I can offer is a framework of an idea. The general idea is that you return two things from your search function, a promise that is resolved only when both ajax calls are resolved and an abort function that can be called to abort the process.

function search(options) {
    var activeAjax = $.ajax(args for first ajax call).then(function(data) {
        // second ajax call changes activeAjax so abort will work
        // on the active ajax call
        activeAjax = $.ajax(args for second ajax call).then(function(data) {
            activeAjax = null;
            // collect your final data here and return it
            // this will be the resolved value of the final promise
            return finalData;
        });
        return activeAjax;
    });

    return {
        promise: activeAjax,
        abort: function() {
            if (activeAjax) {
                activeAjax.abort();
            }
        }
    };
}

// usage:
var searchInProgress = search(...);
searchInProgress.promise.then(function(data) {
    // search finished successfully, answer is in data
}, function(err) {
    // either one of the promises failed
});

// and, at any time, you can call searchInProgress.abort();

Post a Comment for "Rejecting Inner Promise After Initial Promise Has Succeeded?"