async 와 await
async/await 구문은 Promise 객체를 다루는 코드(Promise Chaining 코드 등)를 사람들이 좀더 익숙하게 느끼는
동기 실행 스타일의 코드로 작성할 수 있게 해주는 Syntactic sugar이다.
아래는 promise 를 다루는 코드와 async/await 문법을 비교한것이다. 두 결과는 동일하다.
Promise
fetch('https://www.google.com')
.then((response) => response.text())
.then((result) => {
console.log('a');
})
.catch((error) => {
console.log(error);
})
.finally(() => {
console.log('exit')
});
async 와 await
async function fetchAndPrint() {
try {
const response = await fetch('https://www.google.com');
const result = await response.text();
console.log('a');
} catch(error) {
console.log(error);
} finally {
console.log('exit');
}
}
fetchAndPrint();
'언어 > JavaScript' 카테고리의 다른 글
[JavaScript] 스코프 체인과 호이스팅 (0) | 2023.12.01 |
---|---|
[JavaScript] 자바스크립트 엔진 개요 (0) | 2023.11.28 |
[JavaScript] Promise 객체 등장 배경 (0) | 2023.11.03 |
[JavaScript] const 와 불변(immutable) (0) | 2023.10.27 |