回调函数返回值 [英] Return value from callback function

查看:565
本文介绍了回调函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个函数,调用另一个(在浏览器中的集成函数),像这样:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆