본문 바로가기
자바스크립트

ES2022에서 새로 추가된 top-level await

by 창고관리장 2024. 7. 25.

 

Top-level await

 

내가 코딩을 본격적으로 하기 전인 2022년 6월에 ES2022가 발표되었다. 여기서 오늘 내가 새로 알게된 기능 하나가 포함되었다.

 

여러가지가 발표되었지만, 그중에서도 top-level await 기능이다.

 

비동기 처리를 위해서는 async와 await는 항상 함께 사용한다. 자바스크립트 문법 규칙이기도 하고, 사용할 때는 짝꿍이라고 생각하면서 사용했다.

 

그래서 async 내부에서 await를 사용해야 문법 에러가 뜨지 않았는데, top-level await는 모듈의 최상단 레벨에서 async없이도 모듈화된 자바스크립트 파일들이 마치 하나의 async 덩어리처럼 동작하여 육안상으로 await만으로도 비동기 처리가 잘 되도록 만들어졌다.

💡 최상단 레벨이란 각 모듈 파일의 최상단, 즉 함수나 블록의 내부가 아닌 파일의 가장 바깥 부분을 말한다. top-level await 기능은 이곳에서만 동작하는 것이다.
// 모듈화된 index.js 최상단

const response = await fetch("https://api.example.com/data");
const data = await response.json();

console.log(data);


위 예시코드는 아무것도 없는 모듈화된 index.js 파일의 최상단 코드를 적어본 것이다. ES2022 전에는 이렇게 하면 syntax error가 발생했다.

 

 

중요한 점은 모듈화된 파일에서만 동작하기 때문에 type="module"이 적용되어 있어야 한다.

 

이 기능을 이용해서 비동기 함수를 import 해와서 데이터를 출력하는 예시 코드는 다음과 같다.

// function.js

export async function getEmployees() {
  const response = await fetch('https://learn.example.kr/employees');
  const employees = await response.json();
  return employees;
}

// index.js

import { getEmployees } from "./function.js";

const employees = await getEmployees();
console.log(employees)

// 출력값
[
    {
        "id": 1,
        "name": "Mun",
        "email": "mun@example.kr",
        "department": "engineering"
    },
    {
        "id": 2,
        "name": "Kim",
        "email": "kim@example.kr",
        "department": "engineering"
    },
    {
        "id": 3,
        "name": "Park",
        "email": "park@example.kr",
        "department": "marketing"
    },
]

 

직원 세 명의 데이터를 담고 있는 getEmployees 비동기 함수를 import 해서 top-level await 기능으로 데이터가 출력된 것을 확인할 수 있다.

 

만약 이것을 async를 사용한다면 아래 코드와 같이 똑같이 출력된다.

// index.js

const process = async () => {
  try {
    const employees = await getEmployees();

    console.log(employees);
  } catch (error) {
    console.error("에러 발생");
  }
};

process();

// 출력값
[
    {
        "id": 1,
        "name": "Mun",
        "email": "mun@example.kr",
        "department": "engineering"
    },
    {
        "id": 2,
        "name": "Kim",
        "email": "kim@example.kr",
        "department": "engineering"
    },
    {
        "id": 3,
        "name": "Park",
        "email": "park@example.kr",
        "department": "marketing"
    },
]

 

이 기능이 있다고 해도 async와 await가 짝꿍인 것은 변함이 없다. 자바스크립트 규칙이고, 자주 사용되는 문법인만큼 최신 기능까지 확실히 알아두면 나중에 내가 현업에서 근무할 때 도움이 많이 될 것 같다.