[Study/Web] async 안의 async

SoShy·2024년 2월 1일
0

웹 개발

목록 보기
20/21
post-thumbnail

async 함수 안의 async 함수


async 함수는 async 함수 내에 async 함수를 추가로 작성하는 것도 가능하다.

아래 코드의 흐름을 예상해보고, 예상한 것과 실행 결과과 일치하는 지 확인해보자.

const applyPrivacyRule = async function (users) {
  const resultWithRuleApplied = users.map((user) => {
    const keys = Object.keys(user);
    const userWithoutPrivateInfo = {};
    keys.forEach((key) => {
      if (key !== 'address' && key !== 'phone') {
        userWithoutPrivateInfo[key] = user[key];
      }
    });
    return userWithoutPrivateInfo;
  });

  const p = new Promise((resolve, reject) => {
    setTimeout(() => { resolve(resultWithRuleApplied); }, 2000);
  });
  return p;
};

  async function getUsers() {
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      const result = await response.text();
      const users = JSON.parse(result);
      const resultWithRuleApplied = await applyPrivacyRule(users);
      return resultWithRuleApplied;
    } catch (error) {
      console.log(error);
    } finally {
      console.log('exit');
    }
  }

getUsers().then((result) => { console.log(result); });


💡 이전 글과는 다르게, 이번 글에서는 함수 선언문이 아닌 함수 표현식으로 함수를 나타내었으니, 함수 표현식에서 async 키워드를 사용하는 방법도 함께 기억해두자.

profile
프론트엔드 개발자가 되기 위해 노력 중인 새싹🌱 입니다.

0개의 댓글

관련 채용 정보