回调函数的返回值 [英] Return value from callback function
问题描述
我有几个函数调用另一个(浏览器中的集成函数),如下所示:
I have few functions, which calls another (integrated functions in browser), something like this:
function getItems () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://another.server.tld/", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
items = $("a[href^=/courses/]", xhr.responseText);
}
};
xhr.send();
}
因为我不想在里面写更多的代码,把每个逻辑功能分开,我需要这个函数来返回变量项.
As I don't want to write more code inside and make each logical functionality separated, I need this function to return variable items.
我知道可能会发生一些意外(网络/服务器不可用,响应时间长...)并且该函数可以在从服务器获取数据或发生超时后返回任何内容.
I know there can happen some accidents (network/server is not available, has long-response...) and the function can return anything after gets data from the server or timeout occurs.
推荐答案
这似乎是一个异步请求.我认为您无法从此函数返回数据.
This seems be an async request. I don't think you will be able to return data from this function.
相反,您可以将回调函数作为该函数的参数,并在收到响应时调用该回调.
Instead, you can take a callback function as an argument to this function and call that callback when you have the response back.
function getItems (callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://another.server.tld/", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send();
}
这篇关于回调函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!