Reputation: 26129
I have a code that XMLHttpRequest. It's a object to send request to server and it's asynchronous so when I want to receive the response I need to provide the callback function to onreadystatechange
property of this object. And this function is called after response being received:
function send()
{
XMLHttpRequest req = new...
req.onreadystatechange = answer;
}
function answer()
{
//handling the answer...
}
So it's great but I don't want to use new function to handle answer so I do it anonymous:
function send()
{
XMLHttpRequest req = new...
req.onreadystatechange = function ()
{
//handling the answer...
};
}
But now i want to use the result of send function in another function for example to display result:
display(send())
So how to make this work? Something like:
function send()
{
XMLHttpRequest req = new...
req.onreadystatechange = function ()
{
//handling the answer...
return result; //where result is returned by send function
};
}
Is there any way to do this so that other JS code will still work while this code will handle the response?
Upvotes: 0
Views: 218
Reputation: 340993
You can use synchronous AJAX call:
XMLHttpRequest req = new...
var result = null;
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
result = req.responseText;
}
}
};
req.open('GET', url, false); //async = false
return result;
But this is a poor practice and not an idiomatic way of working with JavaScript. Quoting Synchronous and asynchronous requests:
Note: You shouldn't use synchronous
XMLHttpRequests
because, due to the inherently asynchronous nature of networking, there are various ways memory and events can leak when using synchronous requests.
You know how to use callbacks, why not simply:
send(display)
Upvotes: 0
Reputation: 71939
Inside the readystatechange
handler, the response is available on req.responseText
. You should put your call to display()
inside that event handler.
Upvotes: 0
Reputation: 755457
With asynchronous functions you need to do it the opposite way. Instead of saying display(send())
you need to sue send(display)
function send(callback)
{
XMLHttpRequest req = new...
req.onreadystatechange = function ()
{
//handling the answer...
callback(result);
};
}
Trying to write display(send())
won't work. The send()
function produces a value asynchronously but returns promptly. It can't return the result of the async operation.
Upvotes: 1