Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  68] [ 7]  / answers: 1 / hits: 18601  / 12 Years ago, thu, july 12, 2012, 12:00:00

How can I correctly use jQuery deferreds to delay return of function until async call within function complete + get return value?



This is my current code:



function getFields(page)
{
var dff = $.Deferred();
result = {};
$.ajax( //the async call
{
url: page,
success:
function (data)
{
//work out values for field1 & field 2 from data here
result =
{
'field1' : field1,
'field2' : field2
};
},
complete:
function()
{
dff.resolve(result); //my attempt to return the result
}
}
);
return dff.promise();
}


I want this to print {field1:value1,field2:value2}



var result = getFields('http://something');
console.log(JSON.stringify(result));


However, the value of result appears to be a jQuery object - so I'm doing something wrong, but what?



Thanks!






P.S. Sorry for the newbie question, I am a first time user of deferreds, so I am still grasping the basic concepts.


More From » jquery

 Answers
39

The only way to delay the return of your getFields function would be to set the AJAX async property to false:



   var ajaxPromise = $.ajax(
{
url: page,
async: false // make the call synchronous
}
);


But the jQuery documentation notes that this is deprecated from 1.8 onwards (i.e. it's use is discouraged).



Deferreds don't make AJAX synchronous, instead they make it easier to work with callbacks and asynchronous methods.



From what I can tell of what you're trying to it might work better to do something like this:



function getFields(page)
{
var ajaxPromise = $.ajax( //the async call
{
url: page
}
);

var dff = $.Deferred();
ajaxPromise.then(function(data){

// Possibly access the loaded data in this function.
var result = {
'field1' : field1,
'field2' : field2
};

// Notify listeners that the AJAX call completed successfully.
dff.resolve(result);

}, function(){
// Something went wrong - notify listeners:
dff.reject(/* possibly pass information about the error */);
});

return dff.promise();
}


Then use the promise object like this:



var fieldPromise = getFields('http://something');
fieldPromise.done(function(result){
console.log(JSON.stringify(result));
});


Note that getFields returns a Promise object immediately but you have to wait for the promise to be resolved before you can log out the result.


[#84318] Tuesday, July 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loganl

Total Points: 424
Total Questions: 86
Total Answers: 112

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;