본문 바로가기
js

promise

by 멋진 개구리 2021. 4. 23.
반응형

콜백지옥

만들기전..... 콜백지옥을 보여드림

    //callback 지옥
    function increseAndPrint(n, callback){
      setTimeout(()=>{
        const increased = n +1;
        console.log(increased);
        if (callback){ //콜백이 있다면..
          callback(increased) //호출
        }
      },1000)
    }
increseAndPrint(0, n => {
  increseAndPrint(n, n=> {
    increseAndPrint(n, n=> {
      increseAndPrint(n, n=> {
        increseAndPrint(n, n=> {
          console.log('작업끝');
        });
      });
    });
  });  
});

//1
//2
//3
//4
//5
//작업끝!

프로미스 promise

콜백지옥에서 탈출을 해보자

    //1초 ㄷ위에
    const myPromiseSucc = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('result');
      }, 1000)
    });
    //성공할땐 result
    myPromise.then(result => {
      console.log(result);
    });
    const myPromiseFail = new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(new Error());
      }, 1000)
    });
    //실패할땐 reject
    myPromise.then(reject => {
      console.log(result);
    }).catch(e => {
      console.error();
    });



반응형

'js' 카테고리의 다른 글

axios 장단점 및 사용 법  (0) 2023.05.10
숫자에 콤마 표기 in javascript  (0) 2023.05.10
비동기처리  (0) 2021.04.23
Truthy and Falsy  (0) 2021.04.23
class - food class 만들기  (0) 2021.04.22

댓글