프론트엔드
6. async, await
버밀이
2023. 3. 17. 08:55
async function
async, await는 자바스크립트의 비동기 처리 패턴 중 하나로 기존의 비동기 처리 방식인 콜백 함수와 Promise를 보완하고 가독성을 높여준다.
async, await 기본 문법
//기본
async function callAsy() {
await asyunction() ;
}
//화살표 함수 선언
const callAsy2 = async () => {
await asyunction() ;
}
async, await 예시
const onClickSubmitProduct = async () => {
const result = await createProduct({
variables: {
//variables가 $ 역할을 함
seller: seller,
createProductInput: {
name: name,
detail: detail,
price: Number(price),
},
},
});
async, await 예외 처리
async, await의 예외 처리는 전에 블로그에 올렸던 try ~catch 문을 이용한다.
예외 처리 문법 예시
//화살표 함수 선언
const callAsy2 = async () => {
try {
await asyunction();
} catch (error) {
console.log(error);
}
};
REST-API와 GRAPHQL-API에서의 async, await
rest-API와 graphql-API를 사용해서 요청에대한 응답으로 받는 객체를 변수로 받아서 사용할 수 있는데 응답 결과를 변수로 받기 위해서는 통신의 응답을 받을 때 까지 기다려야 한다. 이 때 async, await를 사용하는 것으로 값을 받아 올때까지 코드가 기다리도록 만들 수 있다.
프로그래밍 예시