javascript - promise

김동하·2020년 9월 25일
0

javascript

목록 보기
30/58

promise는 비동기적 수행을 call back 대신 수행할 수 있는 object

producer

const promise = new Promise((resolve, reject) =>{
  console.log("promise")
  
})

Promise 생성자 함수에 파라메터로 resolve와 reject를 받는다. resolve는 기능이 정상적으로 수행해서 마지막에 최종 데이터를 전달한다. reject는 에러가 생기면 중단한다.

promise는 비동기적으로 실행되기 때문에 promise로 시간이 걸리는 일들을 수행한다. promise는 작성하자마자 네트워크 통신이 발생한다.(executor라는 콜백 함수가 실행됨) 만약 사용자가 원할 때만 네트워크 통신이 발생하게 하려면 promise는 부적합!

const promise = new Promise((resolve, reject) =>{
  console.log("promise")
  setTimeout(()=>{
resolve("done")
  },2000)
})

setTimeout으로 서버에서 데이터를 받아오는 것으로 가정하고 2초가 지난 뒤 서버에서 받아온 데이터를 resolve 콜백 함수를 통해 호출한다.

consumers

then, catch, fianlly로 값을 받아올 수 있다.

promise
.then((val)=>{
  console.log(val) // done
})
.catch(error =>{
  console.log(error)
})
.finally(() =>{
  console.log("finally")

})

promise 변수에 then 메소드(추측)을 사용해서 val을 파라메터로 콜백함수를 만들면 된다. 여기 val은 promise 안에서 resolve 콜백 함수로 받았던 값이다.

그리고 catch 를 이용해서 에러가 발생했을 때 무엇을 할 것인지도 정해준다. finally는 성공유무 관계없이 마지막에 출력되는 기능이다.

promise chaning

const fetchNumber = new Promise((resolve, reject) => {
    setTimeout(() => resolve(1), 1000)
});

fetchNumber
 .then(num => num * 2)
 .then(num => num * 3)
 .then(num => {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve(num - 1), 1000)
    })
})
 .then(num => console.log(num))  // 5, 
 

서버에서 숫자를 받아오는 코드다. 1초가 지나면 1이라는 숫자를 받는다. then은 chain 으로 물리는 관계를 만들 수 있는데 then은 promise도 전달할 수 있다.

에러감지

const getHen = () => 
    new Promise((resolve, reject) => {
        setTimeout(() => resolve("chicken"), 1000)
    })

const getEgg = (hen) => 
    new Promise((resolve, reject) => {
        setTimeout(() => resolve(`${hen} => egg`), 1000)
    })


const cook = (egg) => 
    new Promise((resolve, reject) => {
        setTimeout(() => resolve(`${egg} => cook`), 1000)
    })

getHen()
.then(hen => getEgg(hen))
.then(egg => cook(egg))
.then(meal => console.log(meal))  // chicken => egg => cook

총 3개의 promise를 리턴하는 함수가 있다. getHen 함수를 호출하고 then에 getEgg을 호출하는 식으로 체인을 건다.

const getEgg = (hen) => 
    new Promise((resolve, reject) => {
        setTimeout(() =>  reject(new Error(`${hen} => egg`)), 1000)
    })

만약 egg을 받는 부분에서 에러가 났다면

getHen()
 .then(hen => getEgg(hen))
 .catch(error => {
   return "other egg"
 })
 .then(egg => cook(egg))
 .then(meal => console.log(meal))
 .catch(console.log)

이렇게 에러나 난 부분 밑에 catch를 해주고 다른 것으로 대체할 수 있다.

getHen()
.then(hen => getEgg(hen)) // .then(getEgg)

콜백함수를 전달할 때 받아오는 값을 바로 다음 함수로 호출할 때 그냥 함수만 작성해도 된다.

참고 : https://www.youtube.com/watch?v=JB_yU6Oe2eE&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=12

profile
프론트엔드 개발

0개의 댓글