Async / Await
Async / Await 란?
- Promise를 통해서 비동기 처리를 하는 방법도 있지만, Promise의 단점을 해결하기 위해 ES7에서 async / await 키워드가 추가됨
- async / await 키워드를 사용하면 비동기 코드를 마치 동기 코드처럼 보이게 작성할 수 있음
- callback이나 promise와 같이 비동기 코드를 작성하는 새로운 방법
- async는 함수 이름의 제일 앞에, await은 결과를 기다릴 함수 앞에 작성함
- async는 함수에서 비동기 처리를 위한 promise 동작을 함
- await은 호출되는 함수가 적절한 결과를 반환할 때까지 기다리도록 동작을 함
※ promise는 비동기 처리에서 사용되는 객체로,
promise가 상태를 관리하여 다른 코드가 비동기적으로 실행될 수 있도록 만드는 객체
(axios 또한 promise를 기반으로 만들어짐)
Aysnc / Await 을 이용한 비동기요청 처리 방법
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const users = async() => { | |
console.log(await getData()); | |
return await getData(); | |
} |
Async / Await 의 장점
- 코드가 간결해지고, 가독성이 높아짐
- try / catch로 에러를 핸들링 할 수 있음
- error 확인이 쉬움
Async / Await 사용 예시
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const onClickRegister = async () => { | |
const result = await createProduct({ | |
variables: { | |
seller: seller, | |
createProductInput: { | |
name: name, | |
detail: detail, | |
price: parseInt(price), | |
}, | |
}, | |
}); | |
router.push(`/example/${result.data.createProduct._id}`); | |
}; |
'React > 2022-上' 카테고리의 다른 글
Static, Dynamic Routing (정적 라우팅, 동적 라우팅) (0) | 2022.03.27 |
---|---|
try ~ catch (0) | 2022.03.26 |
Rest-API vs GraphQL-API (0) | 2022.03.24 |
Template Literals (0) | 2022.03.24 |
Git (0) | 2022.03.23 |