javascript 回调函数的返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4897748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:16:24  来源:igfitidea点击:

Return value from callback function

javascriptcallback

提问by Radek Simko

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.

我知道可能会发生一些事故(网络/服务器不可用,响应时间长......)并且该函数可以在从服务器获取数据或发生超时后返回任何内容。

回答by decyclone

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.

相反,您可以将回调函数作为此函数的参数,并在收到响应时调用该回调。

Example:

例子:

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();
}

回答by Victor Nicollet

You're asking for synchronous requests: a function should not return until its return value can be computed even if this involves a hundred milliseconds of asking the server for the data.

您要求同步请求:即使这涉及向服务器询问数据的一百毫秒,函数也不应该在可以计算其返回值之前返回。

By setting the third argument of xhr.opento true, you are using asynchronous requests — telling the browser that you want your function to return before the response from the server was received. Which pretty much means that it cannot return the items, since they have not been received yet.

通过设置xhr.opento的第三个参数true,您正在使用异步请求——告诉浏览器您希望您的函数在收到服务器响应之前返回。这几乎意味着它无法退回物品,因为它们尚未收到。

Of course, using synchronous requests is an user interface pain, because your javascript is basically locked up until the response comes back a few hundred milliseconds later (if you're lucky).

当然,使用同步请求是用户界面的痛苦,因为您的 javascript 基本上被锁定,直到响应在几百毫秒后返回(如果您很幸运)。

What is advised is to correctly architecture your JavaScript code to account for asynchronous communications, and allow values to be returned through a callback instead of return. You don't haveto, but it will save you a lot of pain in the end.

建议是正确构建 JavaScript 代码以考虑异步通信,并允许通过回调而不是return. 你不,但它会为你节省很多的痛苦到底。