I am just beginning to wrap my head around using promises and I could use some guidance on how to get this scenario to work. The code below is from a larger plugin file but I have just included the pieces that I think are relevant.
There is a callback function(callbackBeforeSend) that I will be performing some async geolocation stuff(I've got this working) and I need to hold the ajax call until those functions have completed.
I see in the code that they are using $.Deferred() to handle the ajax response and I am wondering if there is a way to tie the callback function and the initial ajax call into $.Deferred() as well to handle the proper execution order of everything.
So what I would like to happen is
- Callback function fires
- Async stuff happens in callback and returns lat, lng, address
- Ajax fires with lat, lng, address that was returned from callback
Any help would be much appreciated. I still don't understand promises much but I am trying to learn. Thanks!
$.extend(Plugin.prototype, {
    _getData: function (lat, lng, address) {
        var _this = this;
        var d = $.Deferred();
        if (this.settings.callbackBeforeSend) {
            this.settings.callbackBeforeSend.call(this, lat, lng, address);
        }
        $.ajax({
            type         : 'GET',
            url          : this.settings.dataLocation + (this.settings.dataType === 'jsonp' ? (this.settings.dataLocation.match(/\?/) ? '&' : '?') + 'callback=?' : ''),
            // Passing the lat, lng, and address with the AJAX request so they can optionally be used by back-end languages
            data: {
                'origLat' : lat,
                'origLng' : lng,
                'origAddress': address
            },
            dataType     : dataTypeRead,
            jsonpCallback: (this.settings.dataType === 'jsonp' ? this.settings.callbackJsonp : null)
        }).done(function (p) {
            d.resolve(p);
            // Loading remove
            if(_this.settings.loading === true){
                $('.' + _this.settings.formContainer + ' .' + _this.settings.loadingContainer).remove();
            }
        }).fail(d.reject);
        return d.promise();
    }
});
 
     
     
    