Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

How to Wait for a JavaScript jquery async Function to Return a Value

5.00/5 (1 vote)
3 Nov 2015CPOL 9.7K  
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 don't have the time right now to annotate it properly. Hope it helps you just the same.

JavaScript
var temperatureFeedUrl = 'someUrl';

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

                console.log("received new temperature");
                // call some method to do something with the returned data:
                temperatureRenderer.renderLatestTemperature
                (latestTemperature.Temperature, latestTemperature.DeviceId);
            });
        }).set({ time: 5000, auto start: 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();
 }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)