Async/Await
- 비동기 환경에서 실행하지만, 실행이 끝나야 다음을 실행하는 것
- 즉, 실행은 비동기로 이루어지나 실행 순서는 동기적이다.
async
는 키워드가 아니라async function
이다. 즉, async함수로 봐야된다.await
는 키워드다.
function create(param) {
return new Promise((resolve, reject) => {
resolve(param);
});
}
async function getPoint(option) {
const value = await create(option);
console.log(value);
}
getPoint({ point: 100 });
-
async function getPoint(){...}
getPoint를 비동기 함수로 선언하는 것 -
await create()
create함수는 Promise 인스턴스를 생성하여 반환한다. Promise 인스턴스는 비동기 처리를 한다. 따라서console.log(value)
를 실행하고resolve()
가 실행된다. 그러나await
키워드가 존재한다.,- await키워드에 의하여, Promise가 할당되고 나서, 아래의 코드를 실행하는 것이 아니라, Promise의 resolve가 호출될 때 까지 기다리게 된다.
async function
- 비동기 함수를 뜻한다.
async function sports() {
return "축구";
}
Object.prototype.toString.call(sports);
var result = sports();
Object.prototype.toString.call(result);
console.log(result);
엔진이 async function
을 만나면 asyncFunction Object가 생성한다.
Object.prototype.toString.call(sports);
//=> [object AsyncFunction]
- asyncFunction Object는 function Object의 하위 객체로 호출이 가능하다.
asyncFunction이 호출되면 Promise 인스턴스를 반환한다.
var result = sports();
Object.prototype.toString.call(result);
//=> [object Promise]
console.log(result);
// __proto__ : Promise
// [[PromiseState]]: "fulfilled"
// [[PromiseResult]]: "축구"
- "축구"를 반환하지 않고 Promise 인스턴스를 반환한다.
async 함수의 return 값을 처리하려면, then()
을 함수 호출문에 체이닝 해야한다.
sports().then((res) => console.log(res));
console.log("여기먼저");
// 출력
//=> 여기먼저
//=> 축구
-
result 인스턴스는 Promise 객체이므로, Promise.prototype에 연결된 메소드
then()
,catch()
,finally()
를 프로토타입 링크를 이용하여 사용할 수 있다. -
async 함수는 바로 Promise를 반환하고, then과 같은 핸들러 함수는 모든 코드가 다 끝나고 동작한다.(await를 쓰지 않았기 때문에)
async 함수에서 throw가 발생하면, rejected 상태의 Promise가 반환된다.
async function sports(num) {
if (num < 0) return "축구";
else throw "에러";
}
sports(999).then(
(res) => console.log(res),
(rej) => console.log(rej)
);
sports(-10).then(
(res) => console.log(res),
(rej) => console.log(rej)
);
console.log("여기먼저");
// [출력]
//=> 여기먼저
//=> 에러
//=> 축구
- catch를 체이닝해서 사용해도 되고, then의 두 번째 파라미터 핸들러를 작성해서 사용해도 된다
Promise에 생성자 함수를 작성하는 것보다 가독성이 좋다.
await 키워드
await
키워드는 항상 async 함수 안에 위치해야 한다.await 표현식
형태로 작성한다.- 표힌식이 Promise면, Promise를 반환하는 것이 아니라,
resolve()
의 파라미터 값을 반환한다. - 표현식이 Promise가 아니면, 표현식의 평과 결과를 반환한다.
- 표힌식이 Promise면, Promise를 반환하는 것이 아니라,
function create(param) {
return new Promise((resolve, reject) => {
resolve(param);
});
}
async function getPoint(option) {
const value = await create(option);
console.log(value);
}
getPoint({ point: 100 });