How do I return a value from within $.ajax to the outer function? In the example below, I want getProxySrc() to return streamSrc. Also, I don't want to tie up javascript / the page while it's happening... but at the same time, a speci开发者_运维百科fic block of code requires the xml output to proceed. What's the best way of handling that? Some sort of polling?
function getProxySrc(xmlSrc){
var streamSrc;
$.ajax({
type: "GET",
url: xmlSrc,
dataType: "xml",
success: function(xml, textStatus) {
$(xml).find('VideoStream').each(function(){
streamSrc = $(this).text();
console.log("Stream found: " + clip);
return streamSrc;
});
}
});
}
This is already asynchronous, so the script thread is free as soon as the request gets underway.
Unfortunately, since you don't have a synchronous call stack, you can't just return. You'll have to have your success handler call the next part of your process with the values it receives.
Check out some of the javascript promises libraries which are designed to give you a better means of describing workflows that span a lot of async calls.
This project is for MooTools, but the Readme gives a nice description of the nature of the problem, and the nature of the "promises" style solution.
https://github.com/ShiftSpace/promises
JavaScript in the browser is single-threaded. You cannot asynchronously wait for an operation to finish using a loop, for example.
You will either need to have the callback function call another function when the request completes (instead of somehow "returning" to the other function), or make the AJAX request synchronous (by passing in async: false
as part of the request options).
Since you don't want to block, that leaves the callback as the only option. If you are willing to change your design a little, you could add a second parameter to the getProxySrc
function that would be a function to execute when the proxy-src was obtained:
function getProxySrc(xmlSrc, onProxyObtained) {
$.ajax({
//...
success: function(xml, textStatus) {
// ...
if (onProxyObtained) {
onProxyObtained(theProxy);
}
}
});
}
Then, the caller could pass in a function to do whatever they like with the result as soon as it becomes available, with no polling required.
精彩评论