为什么 JQuery.getJSON() 有成功和完成的功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23065907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does JQuery.getJSON() have a success and a done function?
提问by David Thielen
The JQuery documentation for getJSONshows an example of:
var jqxhr = $.getJSON( "example.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
What's the difference between the success function (passed as the 2nd parameter) the the done() function? They seem to be the same thing.
成功函数(作为第二个参数传递)和 done() 函数之间有什么区别?它们似乎是同一回事。
采纳答案by Denys Séguret
Initially, jQuery asynchronous functions weren't returning promises, you had to use the callback.
最初,jQuery 异步函数不返回承诺,您必须使用回调。
Then they added the deferred (promise) system but kept the callbacks for compatibility (and because not everybody like deferred).
然后他们添加了延迟(承诺)系统,但为了兼容性保留了回调(因为不是每个人都喜欢延迟)。
From the Deferred object documentation:
从延迟对象文档:
In JavaScript it is common to invoke functions that optionally accept callbacks that are called within that function. For example, inversions prior to jQuery 1.5, asynchronous processes such as jQuery.ajax() accept callbacks to be invoked some time in the near-future upon success, error, and completion of the ajax request.
jQuery.Deferred() introduces several enhancements to the way callbacks are managed and invoked. In particular, jQuery.Deferred() provides flexible ways to provide multiple callbacks, and these callbacks can be invoked regardless of whether the original callback dispatch has already occurred. jQuery Deferred is based on the CommonJS Promises/A design.
在 JavaScript 中,调用可以选择接受在该函数内调用的回调的函数是很常见的。例如,在jQuery 1.5 之前的版本中,诸如 jQuery.ajax() 之类的异步进程接受在不久的将来在成功、错误和完成 ajax 请求时调用的回调。
jQuery.Deferred() 为管理和调用回调的方式引入了多项增强功能。特别是 jQuery.Deferred() 提供了灵活的方式来提供多个回调,这些回调可以被调用而不管原始回调调度是否已经发生。jQuery Deferred 基于 CommonJS Promises/A 设计。
回答by Juan Mendes
They are the same thing. The done function is meant to work like PromiseThat way you can install handlers from the result of the ajax call. It even works if you call done after the asynchronous call finished (by storing the return value)
他们是一样的东西。done 函数旨在像Promise那样工作,这样您就可以根据 ajax 调用的结果安装处理程序。如果在异步调用完成后调用 done (通过存储返回值),它甚至可以工作