0

This has been asked quite a bit on SO, but I couldn't find a resolution to this exact issue.

I'm hoping to synchronously load two functions before calling another function and believe jQuery's $.when().done() should work, but I can't figure it out.

Here's some simplified code, and jsFiddle below (in this version, wrapItUp() fires immediately):

HTML:

<span>-</span>
<a>-</a>

javascript (jQuery):

var num = 0;

function funk1() {
    setTimeout(function() {
        num++;
        $("a").text(num);
    }, 750);
};

function funk2() {
    setTimeout(function() {
        num ++;
        $("a").text(num);
    }, 1500);
};

function wrapItUp() {
    $("span").text(num);
};

$.when(funk1(), funk2()).then(function() {
    wrapItUp()
});

jsFiddle: http://jsfiddle.net/8pLg3jcm/29/

I've also tried including the following in the funk() functions (in this version, wrapItUp() never fires at all):

var dfd = jQuery.Deferred();
...code...
return dfd.promise();
elPastor
  • 8,435
  • 11
  • 53
  • 81
  • 1
    For the love of god, please don't down-vote a well-constructed question unless you're going to leave a helpful comment. – elPastor Sep 21 '18 at 20:10
  • `$.when` doesn't wait on `undefined`, it just silently moves on. (Neither of your functions return a promise) – Kevin B Sep 21 '18 at 20:14
  • 1
    `$.when` takes promises, whereas `funk1` and `funk2` aren't. doing `jQuery.Deferred().promise()` does return one but it's never resolved. – VLAZ Sep 21 '18 at 20:14
  • Right, and as stated, I've tried `var dfd = jQuery.Deferred()` + code + `return dfd.promise()` to each of the functions and the problem there is that then `wrapItUp()` never fires at all. – elPastor Sep 21 '18 at 20:19
  • @vlaz - can you elaborate on the resolution part of your comment? – elPastor Sep 21 '18 at 20:22
  • A promise is something that will "be done" in the future. The term is "resolve" as in, "resolve a promise". To do that, you need to call `dfd.resolve()` to signal that the promise is not a potential point in the future any more but it's finished and `done`, `fail`, `complete`, etc stored callbacks will be fired as appropriate. – VLAZ Sep 21 '18 at 20:32
  • http://jsfiddle.net/csy5wtnd/1/ small dummy example of a deferred with funk1. – Taplar Sep 21 '18 at 20:34
  • @vlaz & @Taplar - Thank you both! Taplar, your example did the trick. I was returning a resolution outside of the `setTimeout()` – elPastor Sep 21 '18 at 20:39

0 Answers0