0

Hi I'm pretty new to javascript and I have some questions regarding how .done() works with the .getJSON() function. Here is an example:

array1 = [];

loaded = false;

var req = $.getJSON("url", function(json) {
    $.each(json, function(i, item) {
        array1.push(item.name);
    });
});

req.done(function(){   
    loaded = true;
    func(array1);
});

Does the .done() function wait until the code in the callback function passed as a parameter is executed first, or is there a chance that the .done() function will fire and finish before the callback function. For an example, is there a chance that .done() will execute before the array has been filled up with all the data?

In the given example, is there any utility to doing things like this? Besides the ability to call .done() later than the success callback function?

If I want to call func(array1) as soon as the array is filled up with all the data retrieved, is it better to do it in the callback function or in .done()?

  • 4
    a) don't use `done`, use `then` instead b) don't both pass a callback *and* use `then`. Just do all the work in the `then` callback (which also receives a `json` argument). – Bergi Oct 18 '20 at 15:39
  • No. GetJson works against promises so all is being done in specific order. Instantiating with fulfilling or rejecting once the criteria has been met – Raphael Oct 18 '20 at 15:41
  • @Bergi I haven't seen anything about .then() in the JQuery documentation on getJSON. Why is .then() better than using the callback or .done() and where can I read about it? – TwoheadedFetus Oct 18 '20 at 15:49
  • @Raphael what do you mean by in specific order, what gets called first? – TwoheadedFetus Oct 18 '20 at 15:51
  • 1
    @TwoheadedFetus See https://api.jquery.com/jQuery.ajax/#jqXHR (which also documents the call order) and [jQuery deferreds and promises - .then() vs .done()](https://stackoverflow.com/q/5436327/1048572). `done` and `fail` are jQuery-specific, `then` is a standard implementation. – Bergi Oct 18 '20 at 15:58
  • @Bergi Ok thanks I'll read up on that, but still I'm just interested in this situation could func execute before the array is filled with all the data. – TwoheadedFetus Oct 18 '20 at 16:15
  • @TwoheadedFetus No, it can't - see the docs at my [first link](https://api.jquery.com/jQuery.ajax/#callback-functions): "*4. `success` callback option is invoked. […] 5. Promise callbacks […] are invoked, in the order they are registered.*". – Bergi Oct 18 '20 at 19:09
  • @Bergi Ok, thank you, I was having trouble understanding a lot of the terminology used there as I'm still new. So basically based on the order .done() will be called only after the success function has finished? – TwoheadedFetus Oct 18 '20 at 21:19
  • @TwoheadedFetus Yes. But like I said, you shouldn't be using both, so you won't need to rely on that. – Bergi Oct 18 '20 at 23:01
  • @Bergi why is it so bad to use both? – TwoheadedFetus Oct 19 '20 at 21:29

0 Answers0