devops

async & await 테스트 해보기 본문

개발/Javascript

async & await 테스트 해보기

vata500 2022. 7. 14. 01:29
반응형

TEST - 1

function hello(){
    return 'hello';
}

async function helloAsync(){
    return 'hello Async';
}

console.log(hello());

helloAsync().then((res)=>{
    console.log(res);
})

함수앞에 async를 선언하면 자동으로 promise를 반환한다.

async를 선언한 함수의 리턴값은 resolve의 결과값이 된다.

hello Async가 res에 잘들어간 것을 확인할 수 있다.

TEST - 2



function delay(ms){
    return new Promise((resolve)=>{
        setTimeout(resolve, ms)        
    })
}

// 3초 기다린뒤 hello Async 반환하는 것
async function helloAsync(){
    return delay(3000).then(()=>{
        return "hello Async";
    });
}

// await을 이용하면 아래와 같이 간단하게 수정할 수 있다.(await는 async가 선언된 함수에서만 사용가능)
async function helloAsync2(){
    await delay(3000); // await 키워드가 붙은 함수는 모두 동기적으로 실행되고 나서야 다음으로 넘어간다.
    return "hello async";
}

helloAsync().then((res)=>{
    console.log(res);
})


async function main (){
    const res = await helloAsync2();
    console.log(res);
}

결과

 

반응형
Comments