web/back + front

js deferred promise 비동기 처리 관련.

qkqhxla1 2017. 2. 15. 15:56

deferred와 promise는 비동기 처리 관련 자바스크립트 객체다. Promise는 비동기 처리 로직을 추상화 한 객체와 그것을 조작하는 방식을 말한다.

 


deferred와 promise의 개념.

http://stackoverflow.com/questions/17308172/deferred-versus-promise 의 대답인데 쉽게 잘 설명해놓은것 같다.

down voteaccepted

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

deferred object is an object than can create a promise and change its state to resolved or rejected. Deferreds are typically used if you write your own function and want to provide a promise to the calling code. You are the producer of the value.


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


deferred는 promise를 만들수 있고 resolved나 rejected의 상태로 바꿀 수 있다. deferred는 

함수를 만들고, promise에서 함수를 부르려고 할때 일반적으로 사용된다. 즉 개발자가 값을 

설정한다.

promise는 '약속'이라는 뜻에서 알수있듯이 미래의 값에 대한 약속이다. 값을 받기 위해 callback함수를 붙일수 있다. promise는 나에게 주어진 값이고, 개발자는 미래에 결과로 

나온 값을 받는다. 개발자는 promise의 상태를 설정할 수 없으며 promise에 의해 만들어지는 

코드만이 상태를 변경할수 있다.


코드 예제로 간단하게 더 알아보려면 

http://webframeworks.kr/tutorials/angularjs/angularjs_promise_deferred/ 주소를 참조하자. 좋은것 같다..


추가.

왜 종종 deferred.promise()를 리턴하거나, 리턴 하지 않을때가 있을까..? 

http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/ 에 잘 나와있다.

The Promise() method

The Deferred object has another important method named Promise(). This method returns an object with almost the same interface than the Deferred, but it only have the methods to attach callbacks and does not have the methods to resolve and reject.

This is useful when you want to give to the calling API something to subscribe to, but not the ability to resolve or reject the deferred. This code will fail because the promise doesn't have a method "resolve":


Deferred 객체는 Promise()라는 메소드를 가지고 있다. Promise()는 Deferred과 거의 비슷하지만 콜백함수만 붙어서 리턴되고, Deferred에는 있는 resolve나 reject는 없다. 
API를 호출하고나서 resolve나 reject가 굳이 필요 없을때 사용하면 된다. 


더 깊게 들어가서 자세하게 알아보려면 무료로 공개된 한빛미디어 책을 참고하자. 

(여기까지만 봐도 될듯요..)

문제시 삭제하겠습니다!

HANB_JavaScript_Promise-2.pdf


두개의 차이점. 일부 스택오버플로우 글을 가져왔다.

http://stackoverflow.com/questions/6801283/what-are-the-differences-between-deferred-promise-and-future-in-javascript

에 잘 설명되어 있다. 몇개만 가져옴.

In light of apparent dislike for how I've attempted to answer the OP's question. The literal answer is, a promise is something shared w/ other objects, while a deferred should be kept private. Primarily, a deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.

단순하게 말하자면 promise는 다른 객체와 공유된 그런 비동기 객체이고, deferred는 private하게 남겨져야 한다. deferred는 promise로 연장되며, 그 자체로 resolve할수 있지만 promise는 안된다. 


These answers, including the selected answer, are good for introducing promises conceptually, but lacking in specifics of what exactly the differences are in the terminology that arises when using libraries implementing them (and there are important differences).


Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):

스택오버플로우 대답들이 개념적으로는 잘 설명하고 있지만 몇몇 특정 사례들에 대해 설명이 부족하다.

아직 spec이 바뀌고 있는 중이기 때문에 위키피디아나 reference들을 참고했다.


  • Deferred: Never described in popular references, 1 2 3 4 but commonly used by implementations as the arbiter of promise resolution (implementing resolve and reject). 5 6 7

    Sometimes deferreds are also promises (implementing then), 5 6 other times it's seen as more pure to have the Deferred only capable of resolution, and forcing the user to access the promise for using then7

  • Promise: The most all-encompasing word for the strategy under discussion.

    A proxy object storing the result of a target function whose synchronicity we would like to abstract, plus exposing a then function accepting another target function and returning a new promise. 2

deferred : 위에 1,2,3,4에 링크가 걸려진 유명한 references들에서 설명된 적이 없지만 promise의 resolve와 reject를 구현하는데 해결책으로 종종 사용되었다.

deferred는 종종 promises이지만, 대체로 순수하게 deferred로 사용되며 then을 사용해서 promise로 들어가게 한다.

promise : proxy 객체가 다음에 어떤 함수를 실행할지 저장하고 있고, then함수를 사용해서 

새 promise인스턴스를 리턴하는 다른 함수를 실행할수 있다.




공부하면서 적은 거라서 잘못된 지식이 있을 수 있습니다!.


'web > back + front' 카테고리의 다른 글

react.js 무료강좌  (0) 2017.03.09
Blocking-NonBlocking-Synchronous-Asynchronous  (0) 2017.02.20
jquery 이벤트 흐름.  (0) 2017.02.12
jquery 노드,스타일,속성,이벤트 다루기  (0) 2017.02.06
js 정규식 관련.  (0) 2017.02.03