Jquery延迟回调奇怪的问题

发布于 2024-12-02 20:13:25 字数 2684 浏览 2 评论 0原文

我正在玩 jQuery 中的回调和延迟函数,想知道是否有人能告诉我为什么这有效

http:// /jsfiddle.net/austinbv/QVujr/

  get_each_total = function(callback) {
    var requests;
    requests = [];
      var url;
        url = "http://otter.topsy.com/search.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
        return requests.push($.getJSON(url, function(data) {
        }));
    return $.when.apply($, requests).then(function() {
      callback();
    }, function() {
      return alert("There was an error communicating with a remote library, try again in a few");
    });
  };



  get_each_total_broken = function(callback) {
    var requests;
    requests = [];
      var url;
        url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
        return requests.push($.getJSON(url, function(data) {
        }));
    return $.when.apply($, requests).then(function() {
      callback();
    }, function() {
      return alert("There was an error communicating with a remote library, try again in a few");
    });
  };

$(function () {
    get_each_total(alert("success"));
    get_each_total_broken(alert("fail"));
});

这不

http://jsfiddle.net/austinbv/wzve6/

  get_each_total = function(callback) {
    var requests;
    requests = [];
      var url;
        url = "http://otter.topsy.com/search.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
        return requests.push($.getJSON(url, function(data) {
        }));
    return $.when.apply($, requests).then(function() {
      callback();
    }, function() {
      return alert("There was an error communicating with a remote library, try again in a few");
    });
  };



  get_each_total_broken = function(callback) {
    var requests;
    requests = [];
      var url;
        url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
        return requests.push($.getJSON(url, function(data) {
        }));
    return $.when.apply($, requests).then(function() {
      callback();
    }, function() {
      return alert("There was an error communicating with a remote library, try again in a few");
    });
  };

$(function () {
    get_each_total(function () { alert("success")});
    get_each_total_broken(function () {alert("fail")});
});

如您所见,唯一的区别是最后两行,其中匿名函数包装了回调。任何见解都会很好。

I was playing around with call backs and deferred functions in jQuery and was wondering if anyone could tell me why this works

http://jsfiddle.net/austinbv/QVujr/

  get_each_total = function(callback) {
    var requests;
    requests = [];
      var url;
        url = "http://otter.topsy.com/search.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
        return requests.push($.getJSON(url, function(data) {
        }));
    return $.when.apply($, requests).then(function() {
      callback();
    }, function() {
      return alert("There was an error communicating with a remote library, try again in a few");
    });
  };



  get_each_total_broken = function(callback) {
    var requests;
    requests = [];
      var url;
        url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
        return requests.push($.getJSON(url, function(data) {
        }));
    return $.when.apply($, requests).then(function() {
      callback();
    }, function() {
      return alert("There was an error communicating with a remote library, try again in a few");
    });
  };

$(function () {
    get_each_total(alert("success"));
    get_each_total_broken(alert("fail"));
});

and this does not

http://jsfiddle.net/austinbv/wzve6/

  get_each_total = function(callback) {
    var requests;
    requests = [];
      var url;
        url = "http://otter.topsy.com/search.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
        return requests.push($.getJSON(url, function(data) {
        }));
    return $.when.apply($, requests).then(function() {
      callback();
    }, function() {
      return alert("There was an error communicating with a remote library, try again in a few");
    });
  };



  get_each_total_broken = function(callback) {
    var requests;
    requests = [];
      var url;
        url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";
        return requests.push($.getJSON(url, function(data) {
        }));
    return $.when.apply($, requests).then(function() {
      callback();
    }, function() {
      return alert("There was an error communicating with a remote library, try again in a few");
    });
  };

$(function () {
    get_each_total(function () { alert("success")});
    get_each_total_broken(function () {alert("fail")});
});

as you can see the only difference is in the last two lines, where an anonymous function wraps the callback. Any insight would be nice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

牛↙奶布丁 2024-12-09 20:13:25

这段代码:

return requests.push($.getJSON(url, function(data) {
}));

退出您的函数。 callback 永远不会被调用。

PS 当您说唯一的区别是包装回调的匿名函数时,您暗示您还在代码的第一个版本中传递了一个函数。事实并非如此;您试图传入 alert('whatever'); 返回的任何内容,这是未定义

进一步说明:

您的两个函数 (get_each_total, & get_each_total_broken) 都期望参数是一个函数。通过稍后在代码中尝试将其作为函数调用 (callback()),这一点很明显。但是,这一行:

get_each_total(alert("success"));

没有将函数传递给 get_each_total。它相当于以下内容:

var returnedFromAlert = alert("success");
get_each_total(returnedFromAlert);

因此,基本上,您不会将任何内容传递到 get_each_total 函数中。在调用 get_each_total 之前,您会立即收到成功警报。

This piece of code:

return requests.push($.getJSON(url, function(data) {
}));

exits out of your function. The callback is never called.

P.S. When you're saying the only difference is an anonymous function wrapping the callback, you imply that you're also passing a function in the first version of your code. That is not true; you're trying to pass in whatever alert('whatever'); is returning, which is undefined!

Further explanation:

Both of your functions (get_each_total, & get_each_total_broken) expect the parameter to be a function. This is evident by you trying to call it as a function later on in your code (callback()). However, this line:

get_each_total(alert("success"));

does not pass a function to get_each_total. It is equivalent to the following:

var returnedFromAlert = alert("success");
get_each_total(returnedFromAlert);

So, basically, you're not passing anything into your get_each_total function. You get a success alert right away, before get_each_total has been called.

始终不够爱げ你 2024-12-09 20:13:25
get_each_total(function () { alert("success")});

这里有 function (){alert .... 返回一个函数对象

 get_each_total(alert("success"));

,这里 alert("success") 是任何类型的对象 alert( ) 返回,它不是一个函数。

编辑:-为了回应评论,我将进一步澄清。

当浏览器看到

do_something(is_it_complete(arg1, arg2));

它时,它会执行以下步骤:

  1. 获取函数 is_it_complete 并将其称为参数 arg1arg2
  2. 获取函数 do_something 并使用上述结果作为参数来调用它。

当浏览器看到:

do_something(function () { is_it_complete(arg1, arg2) });

它确实:

  1. 创建一个调用 is_it_complete(arg1, arg2) 的函数对象
  2. 获取函数 do_something 并使用上述对象作为参数调用它。

编辑3:-好的,所以在第一个中,它在运行代码之前调用了警报,因此它看起来可以工作。

你有:

get_each_total = function(callback) {
     // ... *snip* 
    return requests.push($.getJSON(url, function(data) {}));
    return $.when.apply($, requests).then(function() {
        // ... *snip*
    });
};

第二次回报永远不会达到。

编辑:-我想在阅读代码后提出一些提示:

var requests;
requests = [];

将样式更改为多余的,

var requests = [];
var url = " ....";

当您不将任何参数传递给回调时,请勿将其包装。

.then(function(){ callback();}) 

它与: 相同

.then(callback);

,正如评论中提到的,您的 url

url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";

应该是

url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js?callback=somevalue&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";

甚至:

url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js"
$.getJSON(url, {
    "callback": "somevalue",
    "apikey": "38A260E9D12A4908B1AF9184B691131",
    "q": "justin bieber",
    "window": "d"
}, function(data){ alert("Got: " + data);});
get_each_total(function () { alert("success")});

here you have the function (){ alert .... that returns a function object

 get_each_total(alert("success"));

here alert("success") is an object of whatever type alert() returns and it is not a function.

Edit:- in respone to the comment i'm going to further clarify.

when the browser sees

do_something(is_it_complete(arg1, arg2));

it goes throught the following steps:

  1. Get the function is_it_complete and call it arguments arg1 and arg2.
  2. get the function do_something and call it with the result of the above as an argument.

When the browser sees:

do_something(function () { is_it_complete(arg1, arg2) });

it does:

  1. Create a function object that calls is_it_complete(arg1, arg2)
  2. Get the function do_something and call it with the above object as an argument.

Edit 3:- Ok so in the first one it called the alert before running your code so it appeared to work.

you have:

get_each_total = function(callback) {
     // ... *snip* 
    return requests.push($.getJSON(url, function(data) {}));
    return $.when.apply($, requests).then(function() {
        // ... *snip*
    });
};

the second return is never reached.

Edit:- thought i would put a few tips after reading the code:

var requests;
requests = [];

is redundant change that style to

var requests = [];
var url = " ....";

When you do not pass any arguments to a callback do no wrap it.

.then(function(){ callback();}) 

it is the same as:

.then(callback);

and as mentioned in the comments your url

url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js?callback=?&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";

Should be

url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js?callback=somevalue&apikey=38A260E9D12A4908B1AF9184B691131&q=justin+bieber&window=d";

or even:

url = "http://otter.topsy.com/hjhkl/sehjkhhkjhkarch.js"
$.getJSON(url, {
    "callback": "somevalue",
    "apikey": "38A260E9D12A4908B1AF9184B691131",
    "q": "justin bieber",
    "window": "d"
}, function(data){ alert("Got: " + data);});
娇妻 2024-12-09 20:13:25

这两个例子都不起作用。 (提示审阅者:这是他所说的最后两行。)

在第一个示例中,您调用 alert(),它会引发警报对话框,甚至在 get_each_total() 函数被调用。Javascript 调用它,显示警报(并给人一种发生了某些事情的错觉),并将 alert() 调用的结果传递给get_each_total() (并且对以下函数中的警报也执行相同的操作)。结果为空。如果曾经调用过回调,则会引发错误。

在第二个示例中,您声明一个函数并将对其的引用传递给 get_each_total(),然后可以通过 callback() 表达式调用该函数。函数是响应 () 运算符的东西,意思是“执行此操作”。如果您的代码成功,它实际上会执行某些操作(显示警报)。

但你的代码没有。转到小提琴并查看控制台,我看到以下消息:“无法加载资源:服务器响应状态为 500(内部服务器错误)。” getJSON() 永远不会触发回调,因为它永远不会成功

[编辑] @austinbv 向我指出我错过了一些东西。 500码是他刻意的测试。但他的代码在 get_each_total_broken() 中仍然被破坏; This returns now from get_each_total_broken行中存在错误的 return

return requests.push($.getJSON(url, function(data) {  }));

when().then() 子句永远不会被调用,因此他永远不会看到错误处理。第一个示例中警报的即时性继续给人一种发生了事情的错觉。

Neither example works. (Hint to reviewers: it is the last two lines of which he speaks.)

In your first example, you call alert(), which raises the alert dialog, even before the get_each_total() function is called. Javascript invokes it, showing the alert (and giving the illusion than something happened), and passes the result of the alert() call to get_each_total() (and does the same with the alert in the following function, too). The result is null. If the callback were ever called, this would raise an error.

In the second example, you're declaring a function and passing a reference to it to get_each_total(), which can then be called via your callback() expression. A function is something that responds to the () operator, meaning "do this." It would actually do something (show the alert) if your code succeeded.

But your code does not. Going to the fiddle, and looking at the console, I see this message: "Failed to load resource: the server responded with a status of 500 (Internal Server Error)." getJSON() never triggers the callback because it never succeeds.

[EDIT] @austinbv pointed out to me that I'd missed something. The 500 code is a deliberate test on his part. But his code is still broken in get_each_total_broken(); there is a misplaced return in the line

return requests.push($.getJSON(url, function(data) {  }));

This returns immediately from get_each_total_broken. The when().then() clause is never invoked, so he never sees the error handling. The immediacy of the alerts in the first example continues to give the illusion that something happened.

笔芯 2024-12-09 20:13:25

您的代码有两个问题:

1)在最后两行代码中:第一个示例是将“alert”方法的执行结果传递给“get_each_total”和“get_each_total_broken”方法。第二个示例是传递一个函数,该函数在执行时将调用“alert”。第二个例子是正确的执行方法。

例如:

function test(v) {
    // do something
    return null;
}

// executes "test" immediately and passes it's result to "someOtherFunction"
someOtherFunction(test(v));
// will pass a function to "someOtherFunction" to be executed later
someOtherFunction(function(){ test("value"); });

2) 您的两个方法中都有 2 个“return”语句。方法中遇到的第一个“返回”将返回其值并退出该方法;从而导致第二个“return”语句永远不会被执行。因此,这两种方法中对“$.when.apply”的调用永远不会被执行。

There are 2 problems with your code:

1) In the last two lines of code: The first example is passing the result of an execution of the "alert" method to both the "get_each_total" and "get_each_total_broken" methods. The second example is passing a function that when executed will call "alert". The second example is the correct method to perform.

For Example:

function test(v) {
    // do something
    return null;
}

// executes "test" immediately and passes it's result to "someOtherFunction"
someOtherFunction(test(v));
// will pass a function to "someOtherFunction" to be executed later
someOtherFunction(function(){ test("value"); });

2) You have 2 "return" statements in both your methods. The first "return" encountered within a method will return it's value and exit the method; thus resulting in the second "return" statement to never be executed. Consiquentially, the call to "$.when.apply" in both methods will never, ever get executed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文