async & await
async와 await라는 특별한 문법을 사용하면 프라미스를 좀 더 편하게 사용할 수 있습니다. async, await는 놀라울 정도로 이해하기 쉽고 사용법도 어렵지 않습니다.
async
function 앞에 위치합니다. async가 붙은 함수는 반드시 프라미스를 반환하고, 프라미스가 아닌 것은 프라미스로 감싸 반환합니다.
async function f() {
return 1;
}
await
자바스크립트는 await 키워드를 만나면 프라미스가 처리될 때까지 기다립니다. 결과는 그 이후 반환됩니다.
// await는 async 함수 안에서만 동작합니다.
let value = await promise;
feth만을 사용한 경우
가져온 데이터를 다른 데이터를 가져오는데 사용하는 경우에 계속하여 .then() 안쪽에 fetch함수를 써야하는 불편함이 있습니다.이를 해결하기 위해서 async & await이 있습니다. await는 promise.then보다 좀 더 세련되게 프라미스 result 값을 얻을 수 있도록 해주는 문법입니다. promise.then보다 가독성 좋고 쓰기도 쉽습니다.
feth만을 사용한 경우
function getPostNCommentData() {
fetch("http://localhost:3000/posts")
.then((response) => response.json())
.then((json) => {
// posts의 데이터를 가져오고 또 comments의 데이터도 가져와서 데이터를 처리하는경우
// 연관되어 가져와야하는 데이터가 많아질수록 복잡해진다.
fetch("http://localhost:3000/comments")
.then((response2) => response2.json())
.then((json2) => {
console.log(json2);
});
});
}
async & await
// async / await
async function getData() {
// fetch만을 사용하는 경우 원래는 then()으로 response가 들어온다.
const response = await fetch("http://localhost:3000/posts");
// 데이터가 들어올때까지 await한다는 의미 밑에줄이 실행되지 않는다.
const json = await response.json();
const response2 = await fetch("http://localhost:3000/comments");
const json2 = await response2.json();
console.log(json2);
}
참고자료
https://ko.javascript.info/async-await
'WEB > JavsScript' 카테고리의 다른 글
[JavsScript] Class와 상속 (0) | 2022.05.31 |
---|---|
[JavaScript] module & try..catch (0) | 2022.05.30 |
[JavaScript] fetch (0) | 2022.05.28 |
[JavaScript] Promise (0) | 2022.05.27 |
[JavaScript] XMLHttpRequest (0) | 2022.05.26 |
댓글