mandag den 2. november 2015

How to wait for a javascript jquery async function to return a value

It took me a little while, and a bit of searching, to find out how to wait for an async function call to return a value.

The below sample shows how. I'm afraid I haven't the time right now to annotate it properly. Hope it helps you just the same.


var temperatureFeedUrl = 'someUrl';

var promise = thisClass.getLatestTemperature(temperatureFeedUrl);
promise.done(function (latestTemperature) {

                console.log("received new tempereature");
                // call some method to do something with the returned data:
                temperatureRenderer.renderLatestTemperature(latestTemperature.Temperature, latestTemperature.DeviceId);
            });
        }).set({ time: 5000, autostart: true });
    });
    
    
getLatestTemperature: function (temperatureFeedUrl) {

        console.log("getLatestTemperature called");
        var latestTemperature = new Object();
        latestTemperature.Temperature = -1;

        var deferred = $.Deferred();

        var jqxhr = $.getJSON(temperatureFeedUrl)
         .done(function (data) {

             latestTemperature.MeasurementDate = data.created_at;
             latestTemperature.Temperature = data.field1;
             latestTemperature.DeviceId = data.field2;
         })
         .fail(function () {
             deferred.resolve(latestTemperature);
         })
         .always(function () {
             deferred.resolve(latestTemperature);
             console.log(latestTemperature.Temperature);
         });

        return deferred.promise();
 }