언어/JavaScript

[JS] async/await/promise

부리부리부리부리 2021. 12. 9. 09:28

과제

async,await,promise,setTimeout를 이용하여 

1초, 2초, 3초, 4초, 5초 간격으로 함수가 동작하도록 구현

 

 

JavaScript는 비동기적 언어이다. 모든 코드가 비동기적으로 돌아간단 것이 아니라

특정 상황(ex : 함수가 Web API 호출, setTimeout )에 코드가 비동기적으로 돌아간다는 얘기인데, 이를 동기적으로 처리할 수 있게 해주는 것들 중 하나가 Promise 객체와 async&await이다. 

 

내가 배운 것에 한해서, async&await은 promise 객체를 인지해 동기적으로 구현해주는 기능을 한다. 

다음은 처음 과제를 받았을 때 내가 짠 코드이다. 

 

async function test(){
    await setTimeout(()=>{
        console.log('1000')
    },1000)
    await setTimeout(()=>{
        console.log('2000')
    },2000)
    await setTimeout(()=>{
        console.log('3000')
    },3000)
    await setTimeout(()=>{
        console.log('4000')
    },4000)
    await setTimeout(()=>{
        console.log('5000')
    },5000)
}
test();

ㅋㅋ쉽네 하고 작동해보니.. 저 모든게 5초 안에 끝나더라..

분명 1초 후 '1000'이 찍히고 또 2초 후 '2000'이 찍히고.. 가 반복되어서 15초 후에 '5000'이 찍힐 줄 알았는데..

 

https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout

 

Combination of async function + await + setTimeout

I am trying to use the new async features and I hope solving my problem will help others in the future. This is my code which is working: async function asyncGenerator() { // other code ...

stackoverflow.com

늘 그렇듯 킹택오버플로우 형님들이 해결해주셨다.. 

 

요약하자면 

setTimeout은 promise객체가 아니기에 async&await이 무용지물이 된 것이었다. 

( async&await은 정말 promise 객체만 받아들이나?) 

 

따라서 setTimeout을 promise 객체에 넣을 필요가 있었기에 코드를 수정했다.

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

async function test(){
    await timeout(1000)
    console.log("1")
    await timeout(2000)
    console.log("2")
    await timeout(3000)
    console.log("3")
    await timeout(4000)
    console.log("4")
    await timeout(5000)
    console.log("5")
}

test();

 

ㅅㄱ용 ^^ 

 

참고 사이트:

- https://elvanov.com/2597

 

[Javascript] 비동기, Promise, async, await 확실하게 이해하기 – Under The Pencil

개요 본 글은 자바스크립트에서 Promise 에 대한 개념을 잡기 위해 작성한 글입니다. 자바스크립트의 기본 문법을 먼저 알아야 이 글을 조금 더 수월하게 보실 수 있습니다. 필자는 Node.js 기반에서

elvanov.com

- https://joshua1988.github.io/web-development/javascript/javascript-asynchronous-operation/