async와 await는 동기적 코드처럼 보이는 비동기 코드를 짤 수 있게 한다.

https://flaviocopes.com/javascript-async-await/

 

Modern Asynchronous JavaScript with Async and Await

Discover the modern approach to asynchronous functions in JavaScript. JavaScript evolved in a very short time from callbacks to Promises, and since ES2017 asynchronous JavaScript is even simpler with the async/await syntax

flaviocopes.com

 

JS는 짧은 기간안에 콜백으로 부터 프로미스로 진화하는 기염을 토했다. 그리고 다시 한번 async/await로 심플 해졌다. 

async 함수는 프로미스와 제너레이터의 합작이다. 그리고 프로미스보다 더 추상적인 함수이다. 즉 async/await는 프로미스를 기초로한다.

 

일단  async/await가 탄생하게 된 이유는 프로미스의 보일러플레이트를 줄이고 프로미스 체인의 한계 때문에 나왔다.

프로미스는 콜백 지옥에서 빠져나오게 만들어 주었지만 사용하는 과정이 복잡했다. 이거 때문에 ES2017에서 async/await를 내놓았다.

 

그럼 이제 코드를 보자

// 프로미스 함수를 만든다. 3초 뒤에 'I did something'를 리턴한다.
const doSomethingAsync = () => {
  return new Promise(resolve => {
    setTimeout(() => resolve('I did something'), 3000)
  })
}

// async로 함수를 만들고 콘솔을 찍는다.
const doSomething = async () => {
  console.log(await doSomethingAsync())
}

console.log('before');
// 실행
doSomething();

console.log('after');

// 콘솔 로그 결과
// before
// after
// I did something

함수 앞에 async 키워드를 넣으면 그게 async 함수이다. async함수는 내부적으로 프로미스를 만들어 프로미스를 리턴한다.

함수 앞에 await 키워드를 붙이면 프로미스 상태 값이 이행, 실패 되면 함수를 호출하게 한다.

 

A ====================================
const aFunction = async () => {
  return 'test'
}

B ====================================
const aFunction = async () => {
  return Promise.resolve('test')
}

A, B 라인의 코드는 같은 코드이다.

 

프로미스로만 만든 함수와 비교해보자. 두개 다 같은 코드이다.

일단 fetch도 프로미스를 리턴한다. ( fetch('주소', 설정객체).then(콜백).catch(콜백); 이런 식으로 사용한다. ajax를 더 쉽게 쓰는 api  )

== A =============================================================
const getFirstUserData = () => {
  return fetch('/users.json') // get users list
    .then(response => response.json()) // parse JSON
    .then(users => users[0]) // pick first user
    .then(user => fetch(`/users/${user.name}`)) // get user data
    .then(userResponse => userResponse.json()) // parse JSON
}

getFirstUserData()

== B =============================================================
const getFirstUserData = async () => {
  const response = await fetch('/users.json') // get users list
  const users = await response.json() // parse JSON
  const user = users[0] // pick first user
  const userResponse = await fetch(`/users/${user.name}`) // get user data
  const userData = await userResponse.json() // parse JSON
  return userData
}

getFirstUserData()

 

+ Recent posts