Node.js의 약속 이해
내가 이해 한 것에서 비동기 코드를 호출하는 세 가지 방법이 있습니다.
- 예를 들어 이벤트
request.on("event", callback);
- 콜백, 예 :
fs.open(path, flags, mode, callback);
- 약속
노드 약속 라이브러리를 찾았 지만 얻지 못했습니다.
누군가 어떤 약속이 무엇인지, 왜 그것을 사용해야하는지 설명 할 수 있습니까?
또한 왜 Node.js에서 제거 되었습니까?
node.js의 약속은 약간의 작업을 약속 한 다음 타임 아웃 처리뿐만 아니라 성공 및 실패를 위해 실행될 별도의 콜백을 가졌습니다. node.js에서 약속을 생각하는 또 다른 방법은 성공과 오류라는 두 가지 이벤트 만 발생시킬 수있는 이미 터라는 것입니다.
약속에 대한 멋진 점은 약속 체인을 종속성 체인으로 결합 할 수 있다는 것입니다 (Promise A 와 Promise B가 완료된 경우에만 Promise C를 수행하십시오 ).
코어 node.js에서 그것들을 제거함으로써 코어 위에 놓을 수있는 다양한 약속의 구현으로 모듈을 구축 할 수있는 가능성을 만들었습니다. 이것들 중 일부는 노드 약속 과 미래 입니다.
이 질문에는 여전히 (내 것과 같은) 많은 견해가 있으므로 다음과 같이 지적하고 싶습니다.
- 노드 약속 은 나에게 다소 죽은 것처럼 보이며 (마지막 커밋은 약 1 년 전) 테스트는 거의 포함되지 않았습니다.
- 선물은 매우 나에게 비 대한 모습을 모듈 심하게 설명되어 있습니다 (그리고 나는 명명 규칙은 단지 나쁜 생각)
- 가장 좋은 방법 은 활발하고 잘 문서화 된 q 프레임 워크 인 것 같습니다 .
약속은 말하자면 "최종"작업의 결과를 나타내는 "사물"입니다. 여기서 주목해야 할 점은 어떤 일이 발생 했을 때 의 세부 사항을 추상화하고 그 일이 일어난 후 발생해야 할 일에 집중할 수 있다는 것입니다. 이로 인해 콜백 내부의 콜백 내부에 콜백이있는 대신 코드가 다음과 같이 깨끗하고 유지 관리 가능한 코드가 생성됩니다.
var request = new Promise(function(resolve, reject) {
//do an ajax call here. or a database request or whatever.
//depending on its results, either call resolve(value) or reject(error)
//where value is the thing which the operation's successful execution returns and
//error is the thing which the operation's failure returns.
});
request.then(function successHandler(result) {
//do something with the result
}, function failureHandler(error) {
//handle
});
약속의 사양은 약속의
then
메소드는 주어진 successHandler 또는 failureHandler 콜백이 완료 될 때 충족되는 새로운 약속을 리턴해야합니다. 즉, 수행해야하는 비동기 작업 세트가 있고 콜백을 사용한 것처럼 작업 순서가 보장되도록 약속을 묶을 수 있습니다. 따라서 콜백 내부의 콜백 내부에 콜백을 전달하는 대신 체인 약속이있는 코드는 다음과 같습니다.
var doStuff = firstAsyncFunction(url) {
return new Promise(function(resolve, reject) {
$.ajax({
url: url,
success: function(data) {
resolve(data);
},
error: function(err) {
reject(err);
}
});
};
doStuff
.then(secondAsyncFunction) //returns a promise
.then(thirdAsyncFunction); //returns a promise
약속에 대한 자세한 내용과 그 약속이 왜 멋진 지 확인하려면 Domenic의 블로그를 확인 하십시오 . http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/
This new tutorial on Promises from the author of PouchDB is probably the best I've seen anywhere. It wisely covers the classic rookie mistakes showing you correct usage patterns and even a few anti-patterns that are still commonly used - even in other tutorials!!
Enjoy!
PS I didn't answer some other parts of this question as they've been well covered by others.
Mike Taulty has a series of videos, each of them less than ten minutes long, describing how the WinJS Promise library works.
These videos are quite informative, and Mike manages to show the power of the Promise API with a few well-chosen code examples.
var twitterUrl = "http://search.twitter.com/search.json?q=windows";
var promise = WinJS.xhr({ url: twitterUrl });
promise = promise.then(
function (xhr) {
},
function (xhr) {
// handle error
});
The treatment of how exceptions are dealt with is particularly good.
In spite of the WinJs references, this is a general interest video series, because the Promise API is broadly similar across its many implementations.
RSVP is a lightweight Promise implementation that passes the Promise/A+ test suite. I quite like the API, because it is similar in style to the WinJS interface.
Update Apr-2014
Incidentally, the WinJS library is now open source.
Another advantage of promises is that error handling and exception throwing and catching is much better than trying to handle that with callbacks.
The bluebird library implements promises and gives you great long stack traces, is very fast, and warns about uncaught errors. It also is faster and uses less memory than the other promise libraries, according to http://bluebirdjs.com/docs/benchmarks.html
What exactly is a Promise ?
A promise is simply an object which represents the result of an async operation. A promise can be in any of the following 3 states :
pending :: This is the initial state, means the promise is neither fulfilled nor rejected.
fulfilled :: This means the promise has been fulfilled, means the value represented by promise is ready to be used.
rejected :: This means the operations failed and hence can't fulfill the promise. Apart from the states, there are three important entities associated to promises which we really need to understand
executor function :: executor function defines the async operation which needs to be performed and whose result is represented by the promise. It starts execution as soon as the promise object is initialized.
resolve :: resolve is a parameters passed to the executor function , and in case the executor runs successfully then this resolve is called passing the result.
reject :: reject is another parameter passed to the executor function , and it is used when the executor function fails. The failure reason can be passed to the reject.
So whenever we create a promise object, we've to provide Executor, Resolve and Reject.
Reference :: Promises
I've been also looking into promises in node.js recently. To date the when.js seems to be the way to go due to its speed and resource use, but the documentation on q.js gave me a lot better understanding. So use when.js but the q.js docs to understand the subject.
From the q.js readme on github:
If a function cannot return a value or throw an exception without blocking, it can return a promise instead. A promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be used as a proxy for a remote object to overcome latency.
참고URL : https://stackoverflow.com/questions/4296505/understanding-promises-in-node-js
'IT story' 카테고리의 다른 글
관리되지 않는 리소스 란 정확히 무엇입니까? (0) | 2020.06.15 |
---|---|
업그레이드 가능한 홈 브루 수식을 어떻게 알 수 있습니까? (0) | 2020.06.15 |
#defining WIN32_LEAN_AND_MEAN에서 정확히 제외하는 것은 무엇입니까? (0) | 2020.06.15 |
혼합 콘텐츠를 허용하도록 Chrome을 사용하는 방법은 무엇입니까? (0) | 2020.06.15 |
0.1을 여러 번 더해도 손실이없는 이유는 무엇입니까? (0) | 2020.06.14 |