비동기 코드를 동기 코드처럼 작성할 수 있게 도와주는 문법이다
- ES2017에 도입된 새로운 키워드
Promise 객체async function f() {
return 10 // 프로미스가 아님
}
let v = f()
console.log(v)
// v는 프로미스 객체이다
// Promise {<fulfilled>: 10}
// >[[Prototype]]: Promise
// >[[PromiseState]]: "fulfilled"
// > [[PromiseResult]]: 10
async 함수 안에서만 동작한다
➡️ async 밖에서 쓰면 SyntaxError 발생
Promise.then보다 가독성이 좋다
// Promise.then 사용
function promiseThen(url) {
let response = fetch(url)
return response
}
promiseThen('https://api.github.com/users/kaya53')
.then(res => console.log(res))
// async/await 사용
async function asyncAwait(url) {
let response = await fetch(url)
if (response.status === 200) {console.log(response)}
else {throw Error}
}
asyncAwait('https://api.github.com/users/kaya')
if ~ else 사용http status code가 200일 때와 200이 아닐 때로 나누어서 예외 처리를 할 수 있다try ~ catch 사용await 이 던진 에러를 try ~ catch를 통해 잡을 수 있다try 문에서 에러를 throw 하지 않으면 catch는 어떤 에러도 받지 못함200이 아닌 status code를 받아도 에러라고 인식하지 않음axios의 편한 점이다, axios는 http status code가 200이 아니면 .catch, catch 문 같은 에러 처리로 넘긴다http 통신 코드만 있는 건 아니니까! (axios는 http 통신을 돕는 라이브러리이다)async function asyncAwait(url) {
try {
let response = await fetch(url)
if (response.status !== 200) {
throw new Error('요청이 실패하였습니다.') // catch로 요청 던지기
}
return response
} catch(err) {
console.log(err)
}
}
asyncAwait('https://api.github.com/users/djoeijowjiof')
async 함수 외부에서 .catch로 체이닝.catch에서 처리할 수도 있다.async function asyncAwait(url) {
let response = await fetch(url)
if (response.status !== 200) {
throw new Error('요청이 실패하였습니다.') // catch로 요청 던지기
return response
}
asyncAwait('https://api.github.com/users/djoeijowjiof')
.catch(err => console.log(err))
async가 아닌 함수에서 async함수를 호출해서 에러 처리를 할 때 .catch 처리할 수 있다async function asyncAwait(url) {
let response = await fetch(url)
if (response.status !== 200) {
throw new Error('요청이 실패하였습니다.')
}
return response
}
function f(url) {
asyncAwait(url)
.then(res => console.log(res))
.catch(err => console.log(err))
}
f('https://api.github.com/users/kaya53')