JS/JavaScript

JavaScript - Async & Await

보라색츄르 2023. 7. 13. 19:11

CallBack Hell(콜백 지옥)

 

콜백 지옥은 JavaScript를 이용한 비동기 프로그래밍시 발생하는 문제로서, 함수의 매개 변수로 넘겨지는 콜백 함수가 반복되어 코드의 들여쓰기 수준이 감당하기 힘들 정도로 깊어지는 현상을 말한다.

timer(1000, function(){  
    console.log('작업');
    timer(1000,function(){
        console.log('작업');
        timer(1000,function(){
            console.log('작업');
            timer(1000,function(){
            	console.log('작업');
                .......
        	});
        });
    });
});

 

 

 

1. Promise 를 활용해 콜백지옥 탈출

timer(1000)
    .then(function(){
        console.log('작업');
        return timer(1000);
    })
    .then(function(){
        console.log('작업');
        return timer(1000);
    })
    .then(function(){
        console.log('작업');
    })

 

 

2. Async 와 Await의 활용해 콜백지옥 탈출

- await : 기다려~ 라는 의미의 함수로, 사용전 유의할 사항은 await은 함수안에 있을때 사용이 가능하다.

- async : await을 사용하기위한 함수로 async가 await이 사용이 가능하다.

 

function timer(time){
    return new Promise(function(resolve){
        setTimeout(function(){resolve(time)}, time);
    });
}

async function run(){
    console.log('start');
    var time = await timer(1000);
    console.log('time', time);
    time = await timer(time+1000);
    console.log('time', time);
    time = await timer(time+1000);
    console.log('time', time);
    console.log('end');
    return time;
}

async function run2(){
    console.log('parent start');
    var time =  await run();
    console.log('time', time);
    console.log('parent end');
}

console.log('parent parent start');
run2().then(function(){
    console.log('parent parent end');
});