从异步调用示例返回响应 [英] Return response from asynchronous call example

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

问题描述

我已多次阅读此stackoverflow帖子我如何返回异步调用的响应?.由于某种原因,我只是不明白.有人可以在这里将问题中的示例作为实际的完整解决方案发布,而不是该帖子的"2.重组代码"部分中提供的逐步指导,这让我感到非常困惑.

I have read this stackoverflow post several times How do I return the response from an asynchronous call?. For some reason, I just do not get it. Could someone post the example in the question here as an actual full working solution instead of the step by step guidance provided in section "2. Restructure Code" of the post which I am finding very confusing.

function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            result = response;
            // return response; // <- tried that one as well
        }
    });

    return result;
}

var result = foo(); // always ends up being `undefined`.

推荐答案

成功函数是一个回调,这意味着它可以随时调用.在这种情况下,它在ajax调用之后被称为 之后,并且返回结果; 在ajax调用之前被称为 before ,这意味着结果在返回之前未分配,这就是为什么它始终未定义的原因.

The success function is a callback, meaning it can be called whenever. In this case, it is being called after the ajax call, and return result; is being called before the ajax call, meaning result is not assigned before returning it, which is why it's always undefined.

我想解决此问题的一种方法是将自己的回调传递给 foo 函数,然后在收到数据时调用它,如下所示:

One way I like to fix this problem is by passing my own callback into the foo function then calling it when I receive the data, like this:

function foo(callback) {
    $.ajax({
        url: '...',
        success: function(response) {
            callback(response) // <-- call it here
        }
    });
}

foo(function(data){
    // use your data here
});

这篇关于从异步调用示例返回响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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