Front-end/JavaScript

JS 비동기 2편 - async

파리외 개발자 2023. 3. 20. 18:07

async await

async함수는 ES8부터 비동기처리를 위해 만들어진 함수 형식이다.

//async await ES8
fetch("https://jsonplaceholder.typicode.com/users")
  .then((res) => res.json())
  .then(console.log);

async function fetchUsers() {
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  const data = await res.json();
  console.log(data);
}

fetchUsers();

fetch는 response를 promise객체 형태로 리턴한다.

일반 함수에 async를 붙이고 api통신을 기다려야 하는 부분에 await을 붙여주면

response를 가공해서 사용할 수 있다.

async를 사용하지 않고 fetch를 사용하면 res변수에는

undefined가 담기게 된다.(api를 기다리지 않고 바로 리턴)

 

Promise와 async

promise

const urls = [
  "https://jsonplaceholder.typicode.com/users",
  "https://jsonplaceholder.typicode.com/posts",
  "https://jsonplaceholder.typicode.com/albums",
];

//promise
Promise.all(urls.map((url) => fetch(url).then((res) => res.json())))
  .then((results) => {
    console.log(results[0]);
    console.log(results[1]);
    console.log(results[2]);
  })
  .catch((err) => console.log(err));

Promise를 사용하면 데이터 호출 시마다

Promise를 호출해줘야 하며 그에 맞는 문법을 작성해줘야 한다.

async

const urls = [
  "https://jsonplaceholder.typicode.com/users",
  "https://jsonplaceholder.typicode.com/posts",
  "https://jsonplaceholder.typicode.com/albums",
];

//async
const getData = async function () {
  try {
    const [users, posts, albums] = await Promise.all(
      urls.map((url) => fetch(url).then((res) => res.json()))
    );
    console.log(users);
    console.log(posts);
    console.log(albums);
  } catch (err) {
    console.log(err);
  }
};

getData();

async함수를 사용하게 되면 일반 함수의 문법을 따르므로

데이터 가공흐름이나 변환을 좀 더 익숙하게 할 수 있고

함수 사용의 이점을 가져올 수 있다.

다만 promise의 catch처럼 에러처리를 따로 지원하지 않아서

try catch문을 사용해줘야 한다는 유의점이 있다.