사용 배경
- async와 await는 Promise의 업데이트다.
- then을 많이 쓰는 것을 지양하고, 코드를 간결하게 쓰기 위해서 사용한다.
사용 방법
- 주의점
- await는 async 함수 안에서만 사용할 수 있다.
- 기존 Promise의 사용 방법
const promiseBasic = () => {
fetch("http://192.168.0.8:5500/index.html")
.then((response) => response.text())
.then((text) => console.log(text))
.catch((err) => console.log(`error : ${err}`));
};
- 개편된 Promise의 사용 방법
const promiseUpdate = async () => {
const response = await fetch("http://192.168.0.8:5500/index.html");
const text = response.text();
console.log(text);
//실험했더니 실패뜸
//const responseText = await fetch("http://192.168.0.8:5500/index.html").text();
//console.log(responseText);
};
※ await는 기본적으로 Promise가 끝나기를 기다린다.
try - catch - finally
- try - catch - finally
- Promise를 async와 await를 통해 사용할 때의 then과 catch
- 사용 예시
const promiseUpdate = async () => {
try{
const response = await fetch("http://192.168.0.8:5500/index.html");
const text = response.text();
console.log(text);
}
catch(err){
err => console.log(err);
}
finally{
console.log("finally");
}
};