비동기 작업을 동기처럼
리액트에서 비동기 처리를 위해 Promise를 사용하지만 Promise의 단점을 보완하기 위해 ES7에서 async, await 키워드가 추가됨
const test1 = async () => {
console.log('test1')
return 1
}
const test2 = () => {
console.log('test2')
}
test1()
.then((value) => {
console.log(value)
})
test2()
간단하게 함수앞에 async를 붙여 비동기 처리를 해줄 수 있다.
그리고 async 함수를 보면 Promise객체가 반환되어 then 메서드를 사용 할 수 있다.
function resloveAfter2Seconds() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('resolved!')
}, 2000)
})
}
function asyncCall() {
console.log('calling')
const result = resloveAfter2Seconds()
console.log(result)
}
asyncCall()
비동기 처리를 하지 않는다면 asyncCall를 호출 했을때, calling과 result가 동시에 콘솔에 찍히게 된다. result의 결과를 보면 resolved가 되기도 전에 result에 값을 담아버린다…
function resloveAfter2Seconds() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('resolved!')
}, 2000)
})
}
async function asyncCall() {
console.log('calling')
const result = await resloveAfter2Seconds()
console.log(result)
}
asyncCall()
Async, Await를 사용하였고 await는 말 그대로 Promise가 처리될 때까지 함수 실행을 기다리게 만들고 프로미스가 처리되면 그 결과와 함께 실행이 재개 된다.
await는 async와 같이 사용해야 하며 그렇지 않으면 syntax error가 발생한다.