Click here to Skip to main content
15,890,557 members
Articles / Programming Languages / Javascript

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
3 Nov 2015CPOL 9.5K   6  
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)


Written By
Denmark Denmark
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --