js

promise

멋진 개구리 2021. 4. 23. 00:58
반응형

콜백지옥

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

    //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();
    });



반응형