Question

I seem to having some issues nesting a Post within a Promise without running into timing issues (or I think they're timing issues...). In my scenario I need a Post to fire within a $.when() but it can't continue/return until it is complete.

I've attempted this with/without a nested $.when for the Post, but am still having no luck. I've broken down my code to only 1 section, as my $.when is much larger:

$.when(calcQualifier()).then(function (status) {
    $("#stuff").append(status);
    return calcTotals(); // working function, not shown
}).then(function (status) {
    $("#stuff").append("Complete");
});

function calcQualifier() {
    var def = $.Deferred();
    var serialized = "" //build json here (works fine)
        $.when(calcQualifier_Post(serialized)).then(function (status) {
            def.resolve("Qualifier Calculated <br/>");
            return def.promise();
        });
}

function calcQualifier_Post(serialized) {
    var def = $.Deferred();
    $.post("/Opportunity/CalculateQualifier/", serialized, 
      function (returnJson) {
        var qualifier = returnJson.Qualifier;
        //update view with qualifier results
        return def.promise();
    });
}

In the above scenario, all other .then() items fire fine, but anything with a Post never seems to fire in the correct order.

Any help would be appreciated!

Était-ce utile?

La solution

Return the promises immediately (before resolving them). If you don't, the .when() doesn't get a reference to the deferred object to know when it has been resolved.

$.when(calcQualifier()).then(function (status) {
    $("#stuff").append(status);
    return calcTotals(); // working function, not shown
}).then(function (status) {
    $("#stuff").append("Complete");
});

function calcQualifier() {
    var def = $.Deferred();
    var serialized = "" //build json here (works fine)
    $.when(calcQualifier_Post(serialized)).then(function (status) {
        def.resolve("Qualifier Calculated <br/>");
    });
    return def.promise();
}

function calcQualifier_Post(serialized) {
    var def = $.Deferred();
    $.post("/Opportunity/CalculateQualifier/", serialized, function (returnJson) {
        var qualifier = returnJson.Qualifier;
        //update view with qualifier results
        def.resolve(true);
    });
    return def.promise();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top