0

I am using $.when and .done to make sure that the close window happens after the data is saved. But, this doesn't seem to work as expected.

The workflow is that, user clicks on a button "Save and Close", which should save the data first, trigger print and close the window. But the save data and close window happens at the same time which makes the print fail.

I have read about when..then and deferred object. Tried to implement it here the following code, sometimes it work but most of the time it would break.

$("#btnSaveAndClose").click(function (event) {
    $.when(zSaveSomeData()).done(function (value) {
        zCloseMyWindow();
    });
});

function zSaveSomeData() {
    return zSaveMasterData(masterdata, function () {  
        return zSaveDetailData();
    });
};

function zSaveMasterData(masterdata, fnAfterSave) {
    return $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '/api/masterdata/',
        data: JSON.stringify(masterdata),
        success: function (data) {
            fnAfterSave();
        }
    });
};

function zSaveDetailData() {
    var selectedDataGroups;
    // some logic here

    zSaveDetails(selectedDataGroups);

};

function zSaveDetails(selectedDataGroups) {
    var deferred = $.Deferred();
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '/api/detaildata/',
        data: JSON.stringify(selectedDataGroups),
        success: function (data) {
            var printableGroupIDs = [];
            $.each(data, function () {
                if (this.IsPrintable)
                    printableGroupIDs.push(this.ID);
            });

            if (printableGroupIDs.length > 0) {
                zPrintGroups(printableGroupIDs);
            }
            deferred.resolve('done');
        }
    });

    zAuditSave();
    return deferred.promise();
};

function zPrintGroups(newGroupIDs) {
    // calls external program to print groups

};

function zCloseWindow() {
    window.close();
};

function zAuditSave() {
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '/api/audit'
        success: function (data) {

        }
    });
};

Only thing is that the save calls other methods inside to same master and details data. There are couple of ajax calls too. An unusual thing is that after the data is saved, there is a call to VB code that actually triggers a Print. I am so confused on why would close window fire before the other methods are executed. Any help would be appreciated.

4
  • return zSaveDetailData(); zCleanUp(); - wait what? Commented Apr 13, 2015 at 18:56
  • What is zAuditSave()? Commented Apr 13, 2015 at 18:58
  • @Bergi, thanks for pointing that out, actually that code was left over from my edit. It is not there. I added return to test but did clean the code. Commented Apr 13, 2015 at 18:58
  • zAuditSave() is another method that call a webApi to audit save. I will add that method too. Commented Apr 13, 2015 at 19:00

3 Answers 3

2

For me the code is overly divided into functions, with some doing little more than fronting for others.

I would prefer to see the click handler as a comprehensive master routine which sequences three promise-returning functions zSaveMasterData(), zSaveDetails() and zAuditSave(), then closes the window. Thus, some of the current functions will be subsumed by the click handler.

$("#btnSaveAndClose").click(function(event) {
    zSaveMasterData(masterdata).then(function() {
        var selectedDataGroups;
        /* some logic here */
        var detailsSaved = zSaveDetails(selectedDataGroups).then(function(data) {
            var printableGroupIDs = $.map(data, function (obj) {
                return obj.IsPrintable ? obj.ID : null;
            });
            if (printableGroupIDs.length > 0) {
                // calls external program to print groups
            }
        });
        // Here, it is assumed that zSaveDetails() and zAuditSave() can be performed in parallel.
        // If the calls need to be sequential, then the code will be slightly different.            
        return $.when(detailsSaved, zAuditSave());
    }).then(function() {
        window.close();
    });
});

function zSaveMasterData(masterdata) {
    return $.ajax({
        type: 'POST',
        url: '/api/masterdata/',
        contentType: 'application/json',
        data: JSON.stringify(masterdata),
    });
};

function zSaveDetails(selectedDataGroups) {
    return $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '/api/detaildata/',
        data: JSON.stringify(selectedDataGroups)
    });
};

function zAuditSave() {
    return $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '/api/audit'
    });
};

Note the returns in the three functions with ajax calls. These returns are vital to the sequencing process.

A potentially bigger issue, not addressed in the question (nor in this answer) is how to recover from errors. Presumably, the database will be inconsistent if the sequence of saves was to fail part way through. It may well be better to ditch this client-side sequencing approach in favour of a server-side transaction that the client sees as a single operation.

Sign up to request clarification or add additional context in comments.

4 Comments

I don't think your usage of $.map does work, though
@Bergi, none of my code is tested and I could easily have made a slip. From memory, jQuery.map() differs from Array.prototype.map() in that the jQuery version (a) filters out an element on null return, and (b) returns a jQuery-wrapped array (hence the need for .get()).
Yeah, it should've been named concatMap for its treatment of null and array values. But actually $.map(arr, fn) does return arrays, while $(arr).map(fn) returns the jquery wrapper.
Ah OK, I should have looked it up in the first place. Documentation also says that "within the function, this refers to the global (window) object". Whoops, edited. Thanks for the catch.
0

The problem here is your code doesn't depend on when fnAfterSave() has completed.

Short answer: don't mix success methods, callbacks, and promises - use one pattern and stick to it - and the easiest pattern to use is promises.

$("#btnSaveAndClose").click(function (event) {
    zSaveSomeData().then(function() { zCloseMyWindow(); });
});

function zSaveSomeData() {
    return zSaveMasterData(masterdata).then(function(data) { zSaveDetailData() });
};

function zSaveMasterData(masterdata) {
    return $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '/api/masterdata/',
        data: JSON.stringify(masterdata)
    });

    //remove success callback here as it breaks the chaining
};

Comments

0

It seems like your problem is that you are doing asynchronous things inside an ajax success callback. The promise returned by $.ajax still resolves immediately after the response is received - and executes your done callback before the asynchronous zSaveDetailData() has finished.

So, to chain asynchronous actions, always use then. Use it even for synchronous actions, it makes the sequence clear.

Don't use success callbacks when you're working with promises. You also don't need deferreds. You might want to have a look at these generic rules as well, especially that you never must forget to return promises from async functions that you want to await.

$("#btnSaveAndClose").click(function (event) {
    zSaveSomeData().then(zCloseMyWindow);
});

function zSaveSomeData() {
    return zSaveMasterData(masterdata).then(zSaveDetailData);
}

function zSaveMasterData(masterdata) {
    return $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '/api/masterdata/',
        data: JSON.stringify(masterdata),
    });
}

function zSaveDetailData() {
    var selectedDataGroups;
    // some logic here

    return zSaveDetails(selectedDataGroups);
//  ^^^^^^
}

function zSaveOrderGroups(selectedDataGroups) {
    return $.ajax({
//  ^^^^^^
        type: 'POST',
        contentType: 'application/json',
        url: '/api/detaildata/',
        data: JSON.stringify(selectedDataGroups)
    }).then(function(data) {
//    ^^^^^^^^^^^^^^^^^^^^^^
        var printableGroupIDs = [];
        $.each(data, function () {
            if (this.IsPrintable)
                 printableGroupIDs.push(this.ID);
        });
        if (printableGroupIDs.length > 0) {
            return zPrintGroups(printableGroupIDs);
//          ^^^^^^
        }
    }).then(zAuditSave);
//    ^^^^^^^^^^^^^^^^^
}

function zPrintGroups(newGroupIDs) {
    // calls external program to print groups
}

function zCloseWindow() {
    window.close();
}

function zAuditSave() {
    return $.ajax({
//  ^^^^^^
        type: 'POST',
        contentType: 'application/json',
        url: '/api/audit'
    });
}

13 Comments

I tried to refactor the code to use just one pattern i.e. promises. Still zCloseWindow() is called before zPrintGroups(). I tried to debug, and found that the control hits the line return zSaveDetails(selectedDataGroups); and then when I step into, the ajax with in zSaveDetails() is executed to save the data and then the control goes straight to zCloseWindow() and close the window hence zPrintGroups() method in zSaveDetails() is never fired.
Maybe you've got .then(zCloseWindow()) instead of .then(zCloseWindow)?
I cross checked, it is zSaveSomeData().then(zCloseWindow);. I also, checked all other method calls, and they look good.
Can you put together a demo somewhere maybe? I'm pretty confident this should work.
Sure, i will try to create something demoable. Not sure how to do ajax call though. But, let me try.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.