//Producer
function gotoCodestates(){
return new Promise ((resolve, reject) => {
setTimeout(() => {resolve('1. go to codestates')}, 100)
})
}
function sitAndCode(){
return new Promise ((resolve, reject) => {
setTimeout(() => {resolve('2. sit and code')}, 100)
})
}
function eatLunch(){
return new Promise ((resolve, reject) => {
setTimeout(() => {resolve('3. eat lunch')}, 100)
})
}
function goToBed(){
return new Promise ((resolve, reject) => {
setTimeout(() => {resolve('4. goToBed')}, 100)
})
}
//Consumer - Promise Chaining
gotoCodestates()
.then(data => {
console.log(data) //'1. go to codestates'
return sitAndCode() //꼭 'return'을 해야한다!!
//return값으로 promise객체 전달
})
.then(data => {
console.log(data) //'2. sit and code'
return eatLunch() // return값으로 promise객체 전달
})
.then(data => {
console.log(data) //'3. eat lunch'
return goToBed() // return값으로 promise객체 전달
})
.then(data => {
console.log(data) //'4. goToBed'
})
//Consumer - async & await
const result = async () => {
const one = await gotoCodestates() //resolve값
console.log(one) // '1. go to codestates'
const two = await sitAndCode()
console.log(two) // '2. sit and code'
const three = await eatLunch()
console.log(three) // '3. eat lunch'
const four = await goToBed()
console.log(four) //'4. goToBed'
}
result();
//'1. go to codestates'
//'2. sit and code'
//'3. eat lunch'
//'4. goToBed'
await로 비동기 함수들을 마치 동기적 program인것처럼 사용.
await은 항상 async 필요하다.
setTimeout의 시간이 다 달라도 이 순서대로 나온다.
'JavaScript' 카테고리의 다른 글
part3 (0) | 2021.09.21 |
---|---|
fetch() API (0) | 2021.09.21 |
callback vs promise vs async & await (0) | 2021.09.20 |
타이머 API ( setTimeout, setInterval, clearInterval) (0) | 2021.09.19 |
비동기함수의 순서를 제어하는 방법 2. Promise (0) | 2021.09.19 |