-
Notifications
You must be signed in to change notification settings - Fork 81
[ES6] Promises(2): the API
이 문서는 http://www.2ality.com/2014/10/es6-promises-api.html 를 번역한 내용입니다.
또한 [ES6] Promises(1):the API 다음 편 입니다.
#목차
- Promises
- 첫번째 예제
- Promises 생성과 사용
- promise 생산(Producing a promise)
- promise의 사용(Consuming a promise)
- 성공 또는 거절만 처리(Only handling fulfillments or rejections)
- 예제(Examples)
- 예제:promisifying XMLHttpRequest
- 예제: delaying an activity
- 예제: timing out a promise(promise의 시간 초과)
- then() 체이닝
- 일반 값으로 해결(Resolving with normal values)
- Resolving with thenable(thenable로 해결)
- 에러 처리
#6. 에러 처리 앞서 언급했듯이, 에러 처리에서 무엇을 반환하든 fulfillment 값이 될 것입니다.(rejection 값이 아닌) 이는 실패 할 경우에 사용 할 수 있는 기본값을 지정 할 수 있다는 걸 의미 합니다.
retrieveFileName()
.catch(function () {
// Something went wrong, use a default value
return 'Untitled.txt';
})
.then(function (fileName) {
...
});##6-1 예외를 잡자(Catching exceptions) executor 안에 예외(Exceptions)는 다음 에러 처리자 에게 전달 되어 집니다.
new Promise(function (resolve, reject) {
throw new Error();
})
.catch(function (err) {
// Handle error here
});then's 매개변수 중 하나에서 발생하는 예외는 다음과 같습니다.
asyncFunc()
.then(function (value) {
throw new Error();
})
.catch(function (reason) {
// Handle error here
});##6-2 에러's 체이닝(Chaining errors)
아래 예제를 보면 에러처리를 제공 하지 않는 then()메서드를 한개 또는 여러 개를 체이닝 하여 사용 할 수 있습니다. 그러면 에러는 에러처리기가 있는 곳 까지 전달 되어집니다.
asyncFunc1()
.then(asyncFunc2)
.then(asyncFunc3)
.catch(function (reason) {
// Something went wrong above
});#7.Composition
이번 섹션은 새로운 것을 생성하기 위해 기존 promises를 구성 하는 법을 설명하고자 합니다. 우리는 이미 promises를 구성하는 방법에 대해 본 적이 있습니다(:
then()을 통한 순차적인 체이닝)
추가적으로Promise.all()과Promise.race()로 promises를 구성하는 법을 제공합니다.
##7-1 Promise.all() 에 의한 map()
Promises가 한가지 좋은 것은 promise기반 함수는 결과를 반환 해주므로, 많은 동기로 작동하는 도구(:라이브러리 tools)가 여전히 작동한다는 것 입니다. 예를 들어, 배열이 제공하는 map() 메서드를 다음과 같이 사용 할 수 있습니다.
var fileUrls = [
'http://example.com/file1.txt',
'http://example.com/file2.txt'
];
var promisedTexts = fileUrls.map(httpGet);아래 예제 에서 promisedTexts는 promises 배열 입니다. Promise.all()은 promises 배열을 받고(thenables과 다른 값은 Promise.resolve()에 의해 promise로 변화됩니다.) 그리고, 모든 promises가 성공(fulfilled)하면, 그것들의 값의 배열로 결과가 전달됩니다.(once all of them are fulfilled, it fulfills with an array of their values:)
Promise.all(promisedTexts)
.then(function (texts) {
texts.forEach(function (text) {
console.log(text);
});
})
.catch(function (reason) {
// Receives first rejection among the promises
});##7-2 Promise.race()를 통한 Timing out
Promise.race()는 promises 배열을 받으며, 새로운 promise P를 반환 합니다.(thenables와 다른 값은 Promise.resolve()를 통해 promises 로 변환 됩니다.) 만약 첫번째 Promise가 성공또는 거절로 설정되면 그 Promise를 반환되어집니다.
아래 timeout을 확장한 Promise.race() 예제를 봅시다.
Promise.race([
httpGet('http://example.com/file.txt'),
delay(5000).then(function () {
throw new Error('Timed out')
});
])
.then(function (text) { ... })
.catch(function (reason) { ... });#8. 항상 비동기인 Promises
promise 라이브러리는 동기(즉시실행) 또는 비동기(현재 상황 이후에 promises실행)적인 결과를 전달 하는 것을 완벽하게 통제 할 수 있습니다.
그러나 **Promise/A+**은 후자의 경우(현재 상황이후에 promises실행)를 사용하길 요구합니다.
then() 메서드를 위해 requirement 를 따르기를 권장 합니다. (It states so via the following requirement (2.2.4) for the then() method:)
실행컨텍스트 스택은 플랫폼 코드를 포함하기 전까지
onFulfilled또는onRejected를 호출 할 수 없습니다.
이 의미는 여러분의 코드는 run-to-completion 에 의존 할 수 있다는 것입니다. 그리고 promises 체이닝은 다른 tasks의 프로세스 시간을 갈망하지 않습니다. (and that chaining promises won’t starve other tasks of processing time)
#9. Cheat sheet: the ECMAScript 6 promise API 이번 섹션은 이 명세에 설명된바와 같이 ECMAScript6 promise API 개요를 둘러봅니다.
##9.1 Glossary(어휘) The promise API is about delivering results asynchronously. A promise object (short: promise) is a stand-in for the result, which is delivered via that object. Promise API는 비동기로 결과를 전달합니다. promise 객체는(짧게 promise로 대체함)
상태:
- promise는 항상 3개중에 1개의 상호배타적인 상태를 가집니다.
- 결과가 준비되기전에는 promise는 pending 상태입니다.
- 만약 결과가 준비됬으면, promise는 fulfilled 상태입니다.
- 만약 에러가 발생하면, promise 는 rejected 입니다.
- 만약 어떤행위가 끝났다라는 것은 promise 상태가 설정됬다는 것입니다.(만약 fulfilled 또는 rejected 이던지간에..)
- promise가 한번 설정되면, 더이상 변하지 않습니다.
- 번역 문서를 읽는 중, 오타나 어색한 문장이 있으면 이슈를 등록해주세요!