Reputation: 3903
I'm using pretty standard setup I think. A click on element to call a function that handles an ajax request.
My limited understanding of variable scope and callbacks when using asynchronous anything and trying to figure out jQuery deferreds is making my feeble brain hurt.
$('<div>')
.on({
click : function(){
console.log(
fetchMyData() // this will be 'undefined' but why?
)
}
})
function fetchMyData(){
$.ajax({
// ajax setup
})
.done(function(response){
console.log( response ); // shows 'hello' as expected
return response;
})
}
I get that the ajax call will not necessarily be done by the time I'm doing the console.log(), since it's asynchronous of course.
So how can I make it such that fetchMyData()
will display the ajax result once it's ready?
Upvotes: 0
Views: 792
Reputation: 71908
So how can I make it such that fetchMyData() will display the ajax result once it's ready?
You've already done that, in the .done
callback. If you want fetchMyData
to return the response, you have to use a synchronous call, which is usually not the right thing to do (because the UI will freeze until the response arrives).
Maybe you want to modify your function to take a callback:
function fetchMyData(thenDoThis){
$.ajax({
// ajax setup
}).done(thenDoThis)
}
function doSomethingWithResponse(response) {
// do something
}
Then call it like this:
fetchMyData(doSomethingWithResponse);
Or like this:
$('<div>').click(function() {
fetchMyData(function(response){
console.log(response);
});
});
Upvotes: 1
Reputation: 5419
You can use jQuery When like this :
$('<div>')
.on({
click : function() {
$.when(fetchMyData()).then(function(data) {
console.log(data);
});
}
});
function fetchMyData(){
return $.ajax({
// ajax setup
});
}
Upvotes: 1
Reputation: 550
You should change what fetchMyData function does. Try returning the promise object.
$('<div>').click(function()
{
var fetchMyDataPromise = fetchMyData() ;
fetchMyDataPromise.done(function(response)
{
console.log(response);
});
});
function fetchMyData()
{
return $.ajax({ // ajax setup });
}
Upvotes: 2