返回从匿名的,异步函数的数据? [英] Returning data from anonymous, asynchronous functions?

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

问题描述

考虑:

function ajaxCall(url, callback) {
    $.ajax({
        type: "GET",
        url: url,
        success: function (data) { // <-- fail point: where does the returned data go, now?
            // do stuff with data
            if ( callback ) {
                var ret = callback();
                if ( ret !== undefined ) {
                    return ret;
                }
            }
        }
    });
}

function fooBar() {
    return ajaxCall('some/url', function () {
        // do stuff
        return some_value;
    }
}

右键,所以基本上,我想preserve的请求,以便浏览器不挂,但仍最终返回值的asynchronousness ...这是一个简单的例子,虽然我大概可以简化它,甚至更多。

Right, so basically, I want to preserve the asynchronousness of the request so the browser doesn't hang, but still return a value in the end... This is a simplified example, even though I could probably simplify it even more.

其实,我看到的唯一障碍是 $之间的过渡AJAX 成功:匿名函数

In fact, the only obstacle I see is the transition between $.ajax and its success: anonymous function.

哼。

推荐答案

您不能使用异步调用这样的回调运行的之后的你调用函数后,早已返回。相反,你需要做的是调用需要的数据作为部分功能(或全部)回调,例如:

You can't use the calls asynchronously like this, the callbacks run later after your calling function has long since returned. Instead, what you need to do is call the function that needs the data as part of the (or the entire) callback, for example:

function ajaxCall(url, callback) {
  $.ajax({
    type: "GET",
    url: url,
    success: callback
  });
}

function fooBar() {
    ajaxCall('some/url', function (data) {
        functionThatNeedsData(data);
    });
}

这只是一个例子来说明这是怎么回事,在实践中它可能仅仅是:

That's just an example to show what's going on, in practice it could just be:

function fooBar() {
  $.get('some/url', functionThatNeedsData);
}

这只是调用你的 functionThatNeedsData 从请求作为第一个参数得到的数据...所以只要服务器的数据来响应,你传递给它在它需要做的,用这些数据做你的工作的其余部分。

This just calls your functionThatNeedsData which gets the data from the request as the first argument...so as soon as the server responds with data, you're passing it on where it needs to do and doing the rest of your work with that data.

这篇关于返回从匿名的,异步函数的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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