본문 바로가기

프로그래밍 기초/기초문법

Async, Await

* 영어표기가 디폴트, 이하 한글표기

* Angular 기준


0. Async

- 비동기 처리 패턴, 비동기 함수

- callback, Promise 의 단점을 보완

- Async 안에서 선언된 await 를 통해 강제로 동기화가 진행됨

 

  1). 장점

        - 무조건 처리해야 하는 부분을 해결함

       - 간단한 문법 (메서드 앞 async, 함수 안 await 적기)

  2). 단점

        - 웹은 대체로 싱글 스레드이며 await 를 무조건 기다리기 때문에 처리 속도에 문제가 발생할 수 있음.

       - 따라서 이 부분에 대한 해결이 없으면 에러 발생 (제대로 체크하지 않으면 나중에 디버그할때 피눈물)

 


1. 활용

- indexDB 처럼 사용할 때 마다 무조건 호출이 필요한 경우.

 

  //호출 하는 함수 앞

  async Function() { 

       ...

      await (db 불러오기) ... }

 

 

 

 

--------------

https://velog.io/@khyup0629/javascript-async%EC%99%80-await%EC%9D%98-%EA%B0%9C%EB%85%90%EA%B3%BC-%EC%82%AC%EC%9A%A9%EB%B2%95

 

delay() {
    console.log('#$##$#$#$ 3')
    return new Promise<void>((resolve, reject) => {
      console.log('#$##$#$#$ 4')
      setTimeout(() => resolve(), 5000);
    })
  }

async getApple() {
    console.log('#$##$#$#$ 2')
    await this.delay();
    console.log('#$##$#$#$ 5')
    return "apple";
  }

 

 

 

 

https://soft91.tistory.com/54

  fetchDatas: string = '';
  fetchData() {
    const result = this.fetchDatas // 백엔드로부터 데이터를 불러오는데 5초의 시간이 걸림
    return result
  }

  async getDataOne() {
    const result = await this.fetchData() // 데이터를 가져오는데 3초의 시간이 걸린다면 이를 기다려줌
    return result
  }

  async getDataTwo() {
    const result = await this.fetchData() // 데이터를 가져오는데 3초의 시간이 걸린다면 이를 기다려줌
    return result
  }

  async getDataThree() {
    const data1 = await this.getDataOne() // 3초의 시간이 걸림
    const data2 = await this.getDataTwo() // data1 가져온 뒤 실행. 3초의 시간이 걸림
    return `${data1}, ${data2}`
  }