JavaScript 비동기 작업 Promise, async, await 알아보기
포스트
취소

JavaScript 비동기 작업 Promise, async, await 알아보기

안녕하세요. Narvis2 입니다.
이번 시간에는 JavaScript에서 비동기 처리에 사용되는 promise, async, await에 대하여 알아보도록 하겠습니다.

🍀 Promise


  • 비동기 작업의 단위
  • new Promise를 사용하여 생성
  • 첫 번째 인수 resolve 👇
    • 비동기 작업이 성공했을 경우 호출됨
  • 두 번째 인수 reject
    • 비동기 작업이 실패했을 경우 호출됨
  • new Promise(...)의 인스턴스를 생성하는 순간 여기에 할당된 비동기 작업은 바로 실행됨

    즉, new Promise를 하는 순간 비동기 작업이 시작

  • then 👉 해당 Promise가 성공했을 때의 동작을 지정, 함수를 받음
  • chatch 👉 해당 Promise가 실패했을 때의 동작을 지정, 함수를 받음

    예제👇

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    const promise1 = new Promise((resolve, reject) => {
      resolve();
    });
    
    promise
      .then(() => {
        console.log("then!");
      })
      .catch(() => {
        console.log("catch!");
      });
    
  • 재사용 👉 비동기 작업이 있을때 마다 new Promise를 할 필요 없이 returnnew Promise를 하게되면 재사용이 가능함

    예제 ) 재사용 👇

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    function startAsync(age) {
      return new Promise((resolve, reject) => {
        if (age > 20) resolve();
        else reject();
      });
    }
    
    const promise1 = startAsync(25);
    promise1
      .then(() => {
        console.log("1 then!");
      })
      .catch(() => {
        console.log("1 catch!");
      });
    
    const promise2 = startAsync(15);
    promise2
      .then(() => {
        console.log("2 then!");
      })
      .catch(() => {
        console.log("2 then!");
      });
    
  • 작업 결과 전달 👉 resolve, reject함수에 인자를 전달함으로써 thencatch함수에서 비동기 작업으로부터 정보를 얻을 수 있음

    예제 ) 작업 결과 전달 👇

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    function startAsync(age) {
      return new Promise((resolve, reject) => {
        if (age > 20) resolve(`${age} success`);
        else reject(new Error(`${age} is not over 20`));
      });
    }
    
    const promise1 = startAsync(25);
    promise1
      .then((value) => {
        console.log(value);
      })
      .catch((error) => {
        console.error(error);
      });
    
    const promise2 = startAsync(15);
    promise2
      .then((value) => {
        console.log(value);
      })
      .catch((error) => {
        console.error(error);
      });
    

🍀 Async


  • 비동기 작업을 만드는 손쉬운 방법
  • 함수앞에 async 키워드를 붙힘
  • async함수의 return값은 무조건 Promise

    예제 new Promiseasync로 변경 👇

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    async function startAsync(age) {
      if (age > 20) return `${age} success`;
      else throw new Error(`${age} is not over 20`);
    }
    
    const promise1 = startAsync(25);
    promise1
      .then((value) => {
        console.log(value);
      })
      .catch((error) => {
        console.error(error);
      });
    
    const promise2 = startAsync(15);
    promise2
      .then((value) => {
        console.log(value);
      })
      .catch((error) => {
        console.error(error);
      });
    

🍀 Await


  • Promise가 끝날 때까지 기다림
  • Promiseresolve되든지 reject되든지 끝날 때까지 기다리는 함수
  • awaitasync 함수 내부에서만 사용할 수 있음

    예제 👇

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    
    function setTimeoutPromise(delay) {
      return new Promise((resolve) => setTimeout(resolve, delay));
    }
    
    async function startAsync(age) {
      if (age > 20) return `${age} success`;
      else throw new Error(`${age} is not over 20`);
    }
    
    async function startAsyncJobs() {
      await setTimeoutPromise(1000);
      const promise1 = startAsync(25);
    
      try {
        const value = await promise1;
        console.log(value);
      } catch (e) {
        console.error(e);
      }
    
      const promise2 = startAsync(15);
    
      try {
        const value = await promise2;
        console.log(value);
      } catch (e) {
        console.error(e);
      }
    }
    
    startAsyncJobs();
    
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.