then() 메서드는 Promise를 리턴하고 두개의 콜백 함수를 인수로 받습니다. 하나는 Promise가 성공(success)했을 때를 위한 콜백 함수이고, 다른 하나는 실패(failure)했을 때를 위한 콜백 함수입니다.
구문
p.then(onFulfilled, onRejected);
p.then(function(value) {
// 이행(fulfillment)
}, function(reason) {
// 거부
});
매개변수
onFulfilledPromise가 수행될 때 호출되는Function이고, 수행 값(fulfillment value) 하나를 인수로 받습니다.onRejectedPromise가 거부될 때 호출되는Function이고, 거부 이유(rejection reason) 하나를 인수로 받습니다.
설명
then 과 Promise.prototype.catch() 메서드는 promise 를 리턴하기 때문에, chaining 이 가능합니다. — composition 이라고도 합니다.
예
then 메서드 사용
var p1 = new Promise(function(resolve, reject) {
resolve("Success!");
// 또는
// reject ("Error!");
});
p1.then(function(value) {
console.log(value); // 성공!
}, function(reason) {
console.log(reason); // 오류!
});
Chaining
then 메서드는 Promise를 리턴하기 때문에, 이어지는 then 호출들을 손쉽게 chaining 할 수 있습니다. onFulfilled 또는 onRejected 콜백 함수가 리턴하는 값은 자동으로 resolved promise로 wrapping 되기 때문에 다음에 오는 then 이나 catch 메서드로 전달 됩니다.
var p2 = new Promise(function(resolve, reject) {
resolve(1);
});
p2.then(function(value) {
console.log(value); // 1
return value + 1;
}).then(function(value) {
console.log(value); // 2
});
p2.then(function(value) {
console.log(value); // 1
});
Promise 기반 API를 가진 한 함수 위에 또 다른 그러한 함수를 구현하기 위해 chaining을 쓸 수도 있습니다.
function fetch_current_data() {
// 아래의 fetch() API는 Promise를 리턴합니다.
// 이 함수의 최종적인 리턴 값은 then 콜백 함수에서 리턴하는 값(j)인데,
// 위에서 설명 했듯이 resolved promise 로 wrapping 되기 때문에
// 이 함수를 호출하는 곳에서는 then 으로 해당 값(j)을 받을 수 있습니다.
return fetch("current-data.json").then((response) => {
if (response.headers.get("content-type") != "application/json") {
throw new TypeError();
}
var j = response.json();
// fetch_current_data().then() 으로 받게될 이행 값(fulfillment value)
return j;
});
}
스펙
브라우저 호환성
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 32 | 29.0 (29.0) | No support | 19 | 7.1 |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|
| Basic support | No support | 29.0 (29.0) | No support | No support | 8 | 32 |