I have a function foo
which makes an Ajax request. How can I return the response from foo
?
I tried returning the value from the success
callback as well as assigning the response to a local variable inside the function and returning that one, but none of those ways actually return the response.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
Angular1
For people who are using AngularJS, can handle this situation using
Promises
.Here it says,
You can find a nice explanation here also.
Example found in docs mentioned below.
Angular2 and Later
In
Angular2
with look at the following example, but its recommended to useObservables
withAngular2
.}
You can consume that in this way,
See the original post here. But Typescript does not support native es6 Promises, if you want to use it, you might need plugin for that.
Additionally here is the promises spec define here.
Browser can be divided into three parts:
1)Event Loop
2)Web API
3)Event Queue
Event Loop runs for forever i.e kind of infinite loop.Event Queue is where all your function are pushed on some event(example:click) this is one by one carried out of queue and put into Event loop which execute this function and prepares it self for next one after first one is executed.This means Execution of one function doesn't starts till the function before it in queue is executed in event loop.
Now let us think we pushed two functions in a queue one is for getting a data from server and another utilises that data.We pushed the serverRequest() function in queue first then utiliseData() function. serverRequest function goes in event loop and makes a call to server as we never know how much time it will take to get data from server so this process is expected to take time and so we busy our event loop thus hanging our page, that's where Web API come into role it take this function from event loop and deals with server making event loop free so that we can execute next function from queue.The next function in queue is utiliseData() which goes in loop but because of no data available it goes waste and execution of next function continues till end of the queue.(This is called Async calling i.e we can do something else till we get data)
Let suppose our serverRequest() function had a return statement in a code, when we get back data from server Web API will push it in queue at the end of queue. As it get pushed at end in queue we cannot utilise its data as there is no function left in our queue to utilise this data.Thus it is not possible to return something from Async Call.
Thus Solution to this is callback or promise.
A Image from one of the answers here, Correctly explains callback use... We give our function(function utilising data returned from server) to function calling server.
In my Code it is called as
Read here for new methods in ECMA(2016/17) for making async call(@Felix Kling Answer on Top) https://stackoverflow.com/a/14220323/7579856
You are using Ajax incorrectly. The idea is not to have it return anything, but instead hand off the data to something called a callback function, which handles the data.
That is:
Returning anything in the submit handler will not do anything. You must instead either hand off the data, or do what you want with it directly inside the success function.
Short answer is, you have to implement a callback like this:
Use a
callback()
function inside thefoo()
success. Try in this way. It is simple and easy to understand.Using Promise
The most perfect answer to this question is using
Promise
.Usage
But wait...!
There is a problem with using promises!
Why should we use our own custom Promise?
I was using this solution for a while until I figured out there is an error in old browsers:
So i decided to implement my own Promise class for ES3 to below js compilers if its not defined. Just add this code before your main code and then safely use Promise!