0

I want to update the page only when the function "removeDocx" be executed. But in my case, timeout of the timer is perceived as the completion of "wait" function. Where is the problem, and how can I solve it? There is an example of code:

$(function () {
  $.when(wait()).done(function () {
        location.href = location.href;
    });
});
function wait() {
    var pm = { ISN_DOC: GetrcId(document.location.href) };
    if (isNaN(pm.ISN_DOC))
        setTimeout(wait, 500);
    else removeDocx();
}
function removeDocx() {
    var def = $.Deferred();
    var url = "MinPrj/Collage.asmx/clearPattern?isn_doc=" + pm.ISN_DOC;
    $.ajax({
        type: 'POST',
        url: rootpath + url,
        contentType: 'application/json'
    }).done(function (r) {
         def.resolve();
    }).fail(def.reject());
    return def;
}
Kseniya Yudina
  • 137
  • 1
  • 11
  • You are calling `wait()` immediately and passing its return value to `$.when`. Since `wait` doesn't return anything, how do you expect it to work?? – Niet the Dark Absol Apr 01 '16 at 09:43
  • You have no `data` argument to `$.ajax`. Why are you setting a content type of `application/json` when you have no content? – Quentin Apr 01 '16 at 09:46

2 Answers2

2

From the documentation:

jQuery.when( deferreds )
deferreds
Type: Deferred
Zero or more Deferred objects, or plain JavaScript objects.

You are passing a regular function, not a Deferred object so…

If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

First of all fix your removeDocx function. $.ajax already returns a deferred object:

function removeDocx() {
    var url = "MinPrj/Collage.asmx/clearPattern?isn_doc=" + pm.ISN_DOC;
    return $.ajax({
        type: 'POST',
        url: rootpath + url,
        contentType: 'application/json'
    });
}

Now wait function has to return a deferred as well (for it to work with $.when). The problem is that you have to share state between different (pseudo-recursive) calls to wait. Something like this might work:

function wait(def) {
    if (!def) {
        var def = $.Deferred();
    }
    var pm = { ISN_DOC: GetrcId(document.location.href) };
    if (isNaN(pm.ISN_DOC)) {
        setTimeout(function() {
            wait(def);
        }, 500);
    } else {
        $.when(removeDocx()).then(def.resolve);
    }
    return def;
}

The rest of the code stays as it was, i.e. you call wait() without args.

freakish
  • 54,167
  • 9
  • 132
  • 169
  • Thank you. It works! I was more clear to use defered object. – Kseniya Yudina Apr 01 '16 at 10:24
  • But it's not quite correct. If instead location.href = location.href; write location.reload (); - There is an endless loop. And I can not make the implementation of this function by clicking on the button for the project. – Kseniya Yudina Apr 01 '16 at 10:31