0

the following will pass flow back to success chain after handling error:

asyncThatWillFail().then(null, function () {
    //handle error
    return $.Deferred().resolve();
}).then(nextSuccessCallback);

In my particular scenario though, I need to perform multiple parallel async operations in the error handler using the $.when.apply($, promises) approach:

asyncThatWillFail().then(null, function () {
    var promises = [];
    for (var i = 0; i < 3; i++) {
        var dfd = $.Deferred();
        setTimeout(function () {
            dfd.resolve();
        }, 1000);
        promises.push(dfd.promise());
    }
    return $.when.apply($,promises);
}).then(nextSuccessCallback);

I had assumed the above would work since I am returning promise that would eventually be resolved. This jsFiddle though shows that after going through my error handler, neither the following success or error callback are called.

Since the action in the error handler is async, I can't just go ahead and send some resolved value through the return. Not sure where to go from here.

thedarklord47
  • 3,183
  • 3
  • 26
  • 55
  • The promise thing would work, but you have only one `dfd` variable that you are resolving. – Bergi Feb 25 '16 at 02:47

1 Answers1

1

Your issue now is closure ... only the last created promise in the loop of 3 will be resolved due to closure

asyncThatWillFail().then(null, function () {
    log("error handler");
    var promises = [];
    for (var i = 0; i < 3; i++) {
        (function() { // IIFE for a closure
            var dfd = $.Deferred();
            setTimeout(function () {
                dfd.resolve();
            }, 1000);
            promises.push(dfd.promise());
        }());
    }
    return $.when.apply(null,promises);
}).then(nextSuccessCallback, nextFailCallback);

function asyncThatWillFail () {
    var dfd = $.Deferred();
  setTimeout(function(){
      dfd.reject();
  }, 1000)
  return dfd.promise();
}

function nextSuccessCallback () {
    log("success");
}

function nextFailCallback () {
  log("failure");
}

function log (msg) {
    $("#logger").append("<p>"+msg+"</p>");
}

see updated fiddle

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87