Javascript 비동기 Async - await 정리 (설명을 경량화...)
비동기 처리를 하는 경우 자주 사용하게 되는 Async - await을 간단하게 정리했다.
Promise를 모른다면 아래 글을 보고 오는 것을 추천!
https://seokbong.tistory.com/56
Javascript Promise 정리 (설명을 경량화...)
오늘은 Promise를 찾아보았다. 검색을 해보니...? Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다. - https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference..
seokbong.tistory.com
await은 async와 같이 사용되었음.
await을 쓰기 위해서는 function 앞에 aysnc를 선언한 후 해당 함수 내에서 사용해야 함.
참고로 Async 함수는 항상 promise를 반환함.
// 예시
// await apiCallFunction()이 실패하는 상황을 고려하여 try, catch를 사용해야 함.
// (Async - await은 promise 인데 reject가 없기 때문에...)
async function testFunction() {
try{
// apiCallFunc() 이라는 유저의 정보를 가져오는 가상의 함수가 있다고 가정하자.
// 비동기 처리가 필요한 부분
const apiData = await apiCallFunc('api.url/userData');
...
return userData;
} catch (error) {
...
}
}
async에서 return한 값을 받을 때는 then으로 받아야 함.
(Async도 Promise이기 때문에...)
위 코드를 받는다고 가정하면...
// 예시 1
testFunction().then((data) => ...)
// 예시 2 (다음과 같은 방법도 사용 가능함)
const data = await testFunction();
* 추가) Top-level await
await 단독으로 사용이 가능해짐...
- https://v8.dev/features/top-level-await
Top-level await · V8
Top-level await enables developers to use the await keyword outside of async functions. It acts like a big async function causing other modules who import them to wait before they start evaluating their body. The old behavior # When async/await was first i
v8.dev