redgoose(붉은거위)

async와 await에 대하여..

Nest
Development
Category
Javascript
Hit
797
Star
0

좀더 편해라고 하는 기능인건 알고는 있었지만 여태까지 안쓰고 있다보니 돌아가는 프로세스를 이해못하고 있어서 이번에 알아보게 되었다. -_-;
대략적으로 설명하자면 함수안에서 처리를 기다려주고 완료됐다면 다음 라인으로 넘어가거나 리턴보낼 수 있는 기능을 한다.

Basic

일단 기초적으로 어떻게 동작하는지 확인하기 위하여 테스트 코드를 작성해보았다.

function sleep(msg, delay=1000) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(msg);
        }, delay);
    });
}

async function act() {
    let timer = 0;
    let timerInterval = setInterval(() => {
        timer += 1;
        console.log(`${timer.toFixed(1)}s`);
    }, 1000);

    const first = await this.sleep('first', 5000);
    console.log('--------------', first);
    const second = await this.sleep('second', 3000);
    console.log('--------------', second);

    await clearInterval(timerInterval);

    return { first, second };
}

console.log('------------------------------');
this.act().then(result => {
    console.log(result);
});

http://codepen.io/redgoose/pen/ygdBEz (console.log에서 확인가능)

테스트코드를 이렇게 작성했음.

Screen_2017-02-19_PM_25253.png

스크린샷을 보아하니 정직하게 순서대로 실행되는것을 확인할 수 있었다. await이 걸린 라인에서는 done()이 걸릴때까지 기다려주는걸 확인되었다.
await라인에서 단순 리턴으로 값을 받으면 곧장 다음 라인으로 넘어가므로 Promise를 이용해주는것이 좋다.

async/await의 큰 장점은 여러가지 대기열(queue)을 하나씩 처리해주고 그때서야 결과값을 도출해주는 컨테이너 역할을 하는것 같다. ㅎㅎ