programing

지연 대 약속

nasanasas 2020. 10. 24. 10:22
반응형

지연 대 약속


jQuery 버전 외에 Deferred와 Promise의 차이점은 무엇입니까?

필요에 따라 무엇을 사용해야합니까? 나는 단지 fooExecute(). 예를 들어 html div 상태를 전환 하려면 fooStart()만 필요합니다 fooEnd().

//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.???
});

첫째 : $.Promise();존재하지 않기 때문에 사용할 수 없습니다 .

연기 개체 수있는 객체입니다 만들 약속을하고 그 상태를 변경 resolved하거나 rejected. 지연은 일반적으로 자체 함수를 작성하고 호출 코드에 약속을 제공하려는 경우에 사용됩니다. 당신은 가치 생산자 입니다.

약속은 이름이 말하는 것처럼, 미래 가치에 대한 약속입니다. 해당 값을 얻기 위해 콜백을 연결할 수 있습니다. 약속은 귀하에게 "주어진"것이며 귀하 는 미래 가치 수신자 입니다.
약속의 상태를 수정할 수 없습니다. 프라 미스를 생성 한 코드 만이 상태를 변경할 수 있습니다.

예 :

1. ( 생산 ) 자신의 기능에 대한 약속 지원을 제공하려는 경우 지연된 객체를 사용합니다. 값을 계산하고 약속이 해결되는시기를 제어하려고합니다.

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 ) 자신이 promise를 반환하는 함수를 호출하는 경우 지연된 객체를 직접 만들 필요가 없습니다. 그 약속을 돌려 주면됩니다. 이 경우 함수는 값을 생성하지 않고 전달합니다 (종류).

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

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

3. ( 수신 ) 때로는 약속 / 값을 생성하거나 전달하고 싶지 않고 직접 사용하기를 원합니다. 즉, 일부 정보의 수신자입니다.

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

물론 이러한 모든 사용 사례도 혼합 될 수 있습니다. 함수는 값의 수신자 (예 : Ajax 호출)가 될 수 있으며이를 기반으로 다른 값을 계산 (생성) 할 수 있습니다.


관련 질문 :


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

Example from the jQuery documentation:

<!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

This runs a function on each div and executes the .promise code when all .each executions are complete.

참고URL : https://stackoverflow.com/questions/17308172/deferred-versus-promise

반응형