I'm trying to chain functions, and I make a mistake somewhere, but I can't find where...

First, I create a new GeoJSON layer. It works.

var dataLayer = L.geoJSON(null).addTo(myMap);

Next I add some JSON data, it works too.

function getData() {
        var defer = $.Deferred();
        returnData = $.ajax({
                type: "POST",
                dataType: "JSON",
                url: myURL,                          // a normal URL
                error: function (x, e, s) {},        // handle error
                success: ,                           // empty
                complete: function (jqXHR, status) {
                                                     // some other stuff
                                                     // some other stuff
        return defer.promise();

The AJAX query is quite long, about 50-100 ms. I'd like to chain the functions, because the next function should use the data added by getData(). In an other part of the code, when there is a lot of time (eg. some interaction, click from the user), nextFunc() can use the data added by getData(), so I'm quite sure, that the code of the functions are OK.

But if I'd like to call an other function immediately after getData() completed


the nextFunc() function doesn't wait, it starts immediately after getData() started.

How can I force nextFunc() to wait until getData() is done?

1 Answer 1


I'd just leave jQuery's deferreds behind and switch everything to Promises and fetch()es.

function getData() {
  return fetch(myURL, { /* stuff for post */ })
    .then(function(response) { return response.json() })
    .then(function(json) { dataLayer.addData(json); })
    .catch(function(error) { /* handle errors if any */ }


Note it's getData.then(nextFunc) and not getData.then(nextFunc()). That would be the equivalent of getData.then(/* return value of having executed nextFunc immediately */)

  • Thanks. I can't figure out, in this case how to pass variables to nextFunc.
    – Pál Rudan
    May 4, 2021 at 6:51

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.