For example I have a function:
var f1 = function(arg) {
var a;
$.ajax({
...
success: function(data) {
a = f2(data);
//return a;
}
});
//return a;
}
var f3 = function() {
a = f1(arg);
}
How can I return a
after AJAX get data
in f1
?
You can't return the result of your ajax request since the request is asynchronous (and synchronous ajax requests are a terrible idea).
Your best bet will be to pass your own callback into f1
var f1 = function(arg, callback) {
$.ajax({
success: function(data) {
callback(data);
}
});
}
Then you'd call f1
like this:
f1(arg, function(data) {
var a = f2(data);
alert(a);
}
);
Short, easy answer: you can't.
You could make a
a global, but you're subject to timing issues.
Better to either:
.when
/.then
construct, orIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With