如何使函数返回其内部函数的值

How to make function that returns it's inner-function's value?

本文关键字:内部函数 返回 何使 函数      更新时间:2023-09-26

这对你来说可能是显而易见的,但我不明白。

我需要让函数返回它的内部函数的值。换句话说,我有函数get_users(),它必须返回JSON对象。该JSON对象由$.post(内置jQuery)获得。

function get_users() {    
    return
        $.post(
            url_base + 'travel/trip/get_users/' + trip_id,
            function(response) {    
                return response;    
            },
            'json'
        );    
}

(以上是我试图做的,但它返回undefined -真是一个惊喜)

由于变量作用域,我不能在内部函数中创建变量,因为它在主函数中是不可见的。我也不想使用全局变量。寻找更好的解决方案!

谢谢你的建议!

为什么要反对AJAX的异步特性?在使用AJAX时,应该习惯使用事件和回调,而不是编写顺序代码。你不能返回内部内容。原因很简单,这个内部函数可能比外部函数执行得晚得多。因此,外部函数将在成功回调执行之前返回结果。

正确的方法是:

function get_users() {
    $.post(
        url_base + 'travel/trip/get_users/' + trip_id, 
        function(response) {
            // instead of trying to return anything here
            // simply do something with the response
            // Depending on what the server sent you there
            // will be different ways.
            // Here you could also call some other custom function
            // and pass it the response
        }
        'json'
    );
}

不能从ajax调用返回值。(没有设置async false,但这不会是真正的ajax)

当你点击内部返回时,外部函数已经完成了

您将需要使用回调来处理用户。

get_users(function(response) { // this anonymous function is passed in as a parameter
    // do something with the response
});
function get_users(callback) {
    $.post(
        url_base + 'travel/trip/get_users/' + trip_id,
        function(response) {
            // call the passed in function and pass in the response as a parameter
            callback(response);     
        },
        json'
    );
}

您需要了解异步ajax调用的工作原理。

当您调用$.post()时,它启动一个网络调用来执行post,并立即从$.post()调用返回并继续执行javascript的其余部分。它甚至会立即退出函数get_users()

但是,ajax调用还没有完成——它还在进行中。一段时间后,ajax调用将完成,此时将调用定义为function(response) {...}的ajax调用的成功处理程序。只有到那个时候,才知道ajax调用的响应值。

这就是异步ajax的含义。您不能编写像get_users()这样的调用,并期望它获取用户并与用户一起返回。相反,您必须使用回调函数,这些回调函数将在稍后(ajax完成时)被调用,然后您可以继续执行代码的路径。是的,这是不方便的,但这就是javascript中异步ajax调用的工作方式。异步ajax调用的好处是,当ajax调用正在进行时,浏览器和其他javascript代码可以完全处于活动状态。异步ajax调用的代价是它们的编码更加复杂。

对于如何处理这种复杂情况,你有多种选择。首先,您可以进行get_users()调用,然后继续在get_users()内部回调中执行的编程序列,因为这是唯一知道响应(实际用户)的地方。如果您只在代码中的一个地方使用get_users(),那么它可以很好地工作。它看起来像这样:

function get_users() {
    $.post(
        url_base + 'travel/trip/get_users/' + trip_id,
        function(response) {
            // process the user list here and continue whatever other code you
            // need that deals with the user list
        },
        'json'
    );
}

如果您需要在几个不同的地方使用get_users()用于不同的目的,那么您可以将其更改为接受回调本身,并让post调用在ajax调用完成时调用该回调。然后,您将在回调函数中完成对响应的处理:

function get_users(callback) {
    $.post(
        url_base + 'travel/trip/get_users/' + trip_id,
        callback,
        'json'
    );
}

在第二个选项中,您可以像这样调用get_users():

get_users(function(response) {
    // process the user list here and continue whatever other code you
    // need that deals with the user list
});
还有更高级的选项可以使用jQuery的延迟对象。