- promise를 감싸는 함수 앞에 async를 붙인다.
- async function fn() {} / const fn = async () ⇒ {}
- promise 앞에 await을 붙인다.
- await이 붙은 promise의 실행이 완료 되어야 그 다음 코드로 넘어간다.
- 결과 값(resolve의 값)을 변수에 담아서 이후에 사용하면 된다.
- async 함수의 return 값이 있다면, 해당 값을 resolve의 값으로 한 promise가 반환된다.
- 항.상. promise를 반환함에 주의
- promise의 resolve 값으로 promise를 해도 await 한방이면 마지막 곂인 data를 얻을 수 있다.
- Promise를 동기 코드처럼 보이게 짤 수 있다!(depth x)
- 2022년부터 모듈의 최상위 스코프에서 await만을 사용해 특정 비동기 동작이 완료되기 전까지 하위 모듈의 동작을 막을 수 있다.
//a.js - 즉, resp를 async로 감싸주지 않아도 됨 const resp = await fetch('https://jsonplaceholder.typicode.com/users'); const users = resp.json(); export { users}; //b.js - a모듈의 처리가 완료되어야 사용할 수 있다. import { users } from './a.js'; console.log(users); console.log('In usingAwait module');
- catch 처리와 finally는 try-catch로 async 함수 내를 감싸서 대응할 수 있다.
- 코드 변경 해보기
App.js
onClick: async (id) => { const selectedTodo = this.state.todos.find(todo => todo.id === id); this.setState({ ...this.state, selectedTodo }) //댓글 목록 불러오기 const data = await request(`https://kdt-frontend.programmers.co.kr/comments?todo.id=${id}`) this.setState({ ...this.state, comments: data }); } ... //todos 불러오기 this.init = async () => { const data = await request("https://kdt-frontend.programmers.co.kr/todos") this.setState({ ...this.state, todos : data }) }