0

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
                        dataLayer.addData(returnData.resopnseJSON);
                                                     // some other stuff
                        defer.resolve();
                        }
        });
        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

$.when(getData()).done(nextFunc());

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

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

2

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 */ }
}

getData().then(nextFunc);

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 */)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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