1. Promise Chaining
- 비동기 작업을 순차적으로 해야하는 경우가 있습니다.
- 그때 순차적으로 비동기 작업이 끝나고 다음 비동기 작업이 실행해야 하는 경우 사용합니다.
gerProducts()
.then(abc)
.then(bbc)
2. then의 cb의 반환 값
- then의 콜백함수는 여러 타입의 값을 반환할 수 있습니다.
2.1. 값의 반환
let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(1);
}, 1000);
});
promise
.then(function(first) {
console.log('first', first);
return **2**;
}).then(function(**second**) {
console.log(second);
});
- 첫 번째 비동기에서 2를 return하기 때문에 두 번째 비동기는 2가 console.log에 출력됩니다.
2.2. promise 반환
let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(1);
}, 1000);
});
promise
.then(function(first) {
console.log('first', first);
return 2;
})
.then(function(second) {
console.log('second', second);
return new Promise(function(resolve, reject) {
setTimeout(function() {
**resolve(3);**
}, 1000);
});
})
.then**(function(third) {
console.log('third', third);
});**
- 두 번째 비동기에서 Promise를 반환했습니다.
- 두 번째 반환한 Promise의 resolve값이 세 번 then이겠죠.
- 그래서 세 번째 third에 3이 들어갑니다.
Comments