jQuery 延期与承诺

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17308172/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:47:49  来源:igfitidea点击:

Deferred versus promise

jqueryjquery-deferredpromise

提问by fletchsod

What is the difference between Deferred and Promise other than the jQuery versions?

除了 jQuery 版本之外,Deferred 和 Promise 之间有什么区别?

What should I use for my need? I only want to call the fooExecute(). I only need the fooStart()and fooEnd()to toggle the html div status for example.

我应该用什么来满足我的需要?我只想调用fooExecute(). 例如,我只需要fooStart()fooEnd()来切换 html div 状态。

//I'm using jQuery v2.0.0
function fooStart() { /* Start Notification */ }
function fooEnd() { /* End Notification */ }
function fooExecute() { /* Execute the scripts */ }

$('#button1').on('click', function() {
    var deferred1 = $.Deferred();
    var promise1 = $.Promise();

    deferred1.???

    promise1.???
});

回答by Felix Kling

First: You cannot use $.Promise();because it does not exist.

第一:你不能使用,$.Promise();因为它不存在。

A deferred objectis an object that can createa promise and change its state to resolvedor rejected. Deferreds are typically used if you write your own function and want to provide a promise to the calling code. You are the producerof the value.

一个延迟的对象是一个对象,可以创建一个承诺,并改变其状态resolvedrejected。如果您编写自己的函数并希望向调用代码提供承诺,通常会使用延迟。你是价值的生产者

A promiseis, as the name says, a promise about future value. You can attach callbacks to it to get that value. The promise was "given" to you and you are the receiverof the future value.
You cannot modify the state of the promise. Only the code that createdthe promise can change its state.

一个承诺,正如它的名字说,一个关于未来价值的承诺。您可以将回调附加到它以获取该值。承诺是“给予”给你的,你是未来价值的接收者
您不能修改承诺的状态。只有创建承诺的代码才能改变它的状态。

Examples:

例子:

1. (produce) You use deferred objects when you want to provide promise-support for your own functions. You compute a value and want to control when the promise is resolved.

1. ( produce) 当你想为你自己的函数提供承诺支持时,你可以使用延迟对象。您计算一个值并希望控制承诺何时解决。

function callMe() {
    var d = new $.Deferred();
    setTimeout(function() {
        d.resolve('some_value_compute_asynchronously');
    }, 1000);
    return d.promise();
}

callMe().done(function(value) {
    alert(value);
});

2. (forward) If you are calling a function which itself returns a promise, then you don't have to create your own deferred object. You can just return that promise. In this case, the function does not create value, but forwards it (kind of):

2. ( forward) 如果你调用的函数本身返回一个promise,那么你不必创建自己的延迟对象。你可以只回报那个承诺。在这种情况下,该函数不创造价值,而是转发它(有点):

function fetchData() {
    // do some configuration here and pass to `$.ajax`
    return $.ajax({...});
}

fetchData().done(function(response) {
    // ...
});

3. (receive) Sometimes you don't want to create or pass along promises/values, you want to use them directly, i.e. you are the receiver of some information:

3.(接收)有时你不想创建或传递承诺/值,你想直接使用它们,即你是一些信息的接收者:

$('#my_element').fadeOut().promise().done(function() {
    // called when animation is finished
});

Of course, all these use cases can be mixed as well. Your function can be the receiver of value (from an Ajax call for example) and compute (produce) a different value based on that.

当然,所有这些用例也可以混合使用。您的函数可以是值的接收者(例如来自 Ajax 调用)并基于此计算(产生)不同的值。



Related questions:

相关问题:

回答by Codeman

A promise is something you can set on a deferred object that executes when the deferred collection is complete.

承诺是您可以在延迟收集完成时执行的延迟对象上设置的内容。

Example from the jQuery documentation:

jQuery 文档中的示例:

<!DOCTYPE html>
<html>
<head>
  <style>
div {
  height: 50px; width: 50px;
  float: left; margin-right: 10px;
  display: none; background-color: #090;
}
</style>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>

<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>


<script>
$("button").on( "click", function() {
  $("p").append( "Started...");

  $("div").each(function( i ) {
    $( this ).fadeIn().fadeOut( 1000 * (i+1) );
  });

  $( "div" ).promise().done(function() {
    $( "p" ).append( " Finished! " );
  });
});
</script>

</body>
</html>

Here it is in JSFiddle

这是在 JSFiddle

This runs a function on each divand executes the .promisecode when all .eachexecutions are complete.

这会在每个函数上运行一个函数,div.promise在所有.each执行完成后执行代码。