서론

    지난번에는 Callback hell을 해결하기 위해 Promise 문법을 알아보았다.

    하지만 Callback hell을 완벽하게 회피할 수 있는 방법은 아니다.
    그래서 async/await 문법이 ES7부터 나오게 되었다.

    ES7의 async/await에 대해 알아보자.

    본문

    import fs from 'fs'
    
    const openFile = (file: string) => new Promise((resolve, reject) => {
      fs.readFile(file, (err, data) => {
        if(err) reject(err);
        resolve(data);
      });
    });

    지난번 포스트의 openFile 함수다. 이걸 쓰기 위해

    openFile('location')
      .catch((err) => console.log(err))
      .then((data) => console.log(data));

    .then .catch 문법을 사용했다. 하지만 이문법도 .then 이나 .catch 의 callback 함수에서 Promise 를 사용하는 패턴이 생긴다면 Callback hell을 완전히 막을 없다.

    그래서 나온 것이 async/await 문법이다.

    try {
      const data = await openFile('location');
      console.log(data)
    } catch(err) {
      console.log(err)
    }

    callback hell이 완전히 없어졌다!

    하지만 이 문법은 ES7 이하에선 babel을 이용해 Promise로 번역하는 작업이 필요하다.

    그렇다면 Promsie.all([])과 같은 문법은 어떻게 사용하는지 물어볼 수 있다. 간단하다.

    try {
      const data = await Promise.all([openFile('file1'), openFile('file2')];
      console.log(data)
    } catch(err) {
      console.log(err)
    }

    이렇게 사용한다면 data에는 openFile('file1')과 openFile('file2')의 결과가 Array에 담겨서 반환될 것이다.

    Error 처리는 단순히 Try/catch 문을 사용하면 된다!

    결론

    최근 TypeScript와 JavaScript에서는 callback hell을 피하기 위한 노력이 결실을 맺었다.
    하지만 구버전에서 Native로 지원되지 않기 때문에 TypeScript 설정을 조정하거나 Babel을 사용할 필요가 있다.

    하지만 상당히 멋진 문법이 만들어졌다는 것에 존경을 표한다.

    'TypeScript' 카테고리의 다른 글

    Promise는 어떤 건가요?  (0) 2024.05.22
    Posted by dalbodeule