在 Is JavaScript guaranteed to be single-threaded? 很明显,尽管 javascript 是单线程的,但仍然存在一些警告。
我想知道以下伪代码是否总是可预测的(我“使用”jQuery)
var lastReq;
$('#button').click(function()
{
if (lastReq) lastReq.abort();
lastReq = $.ajax(...);
});
这种情况可能是在单击事件和中止之间,来自服务器的数据通过并将事件放入事件队列中。如果这种情况发生在中止之前,则会触发 ajax post 的 succes 事件。 我不知道如何真正测试这种可能的竞争条件。
有人知道这是如何工作的吗?或者如何使用准备好的示例来测试它?
最佳答案
我不知道这个解决方法是否真的有用并且防弹(我正在努力发挥创意),但是,由于 jQuery 1.5 ajax 方法返回一个延迟对象 lastReq
有 state()
方法可用
来自http://api.jquery.com/deferred.state/
The deferred.state() method returns a string representing the current state of the Deferred object. The Deferred object can be in one of three states:
...
"resolved": The Deferred object is in the resolved state, meaning that either deferred.resolve() or deferred.resolveWith() has been called for the object and the doneCallbacks have been called (or are in the process of being called).
这样你就可以像这样重构你的代码
var lastReq;
$('#button').click(function() {
if (lastReq) {
if (lastReq.state() === "resolved") {
return false; /* done() of the previous ajax call is in the process of
being called. Do nothing and wait until the state
is resolved */
}
else {
lastReq.abort();
}
}
lastReq = $.ajax(url).done(function() {
/* do something */
lastReq = null;
});
});
希望这可以帮助您提供一个可行的想法,但我怀疑实际上并不需要这种解决方法
关于javascript - 取消ajax请求: can the handler still be executed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10249591/