await 는 Promise 앞에서만 쓸 수 있을까?
- await 는 Promise 를 처리하기 위해 사용되지만, 다른 타입의 값에도 사용할 수 있다.
1. Promise 가 아닌 값과 함께 사용
async function example() {
const result = await 42;
console.log(result); // 42
}
- 이렇게하면, 해당 값은 자동으로 resolved Promise 로 감싸진다.
- Promise 와 유사한 인터페이스를 가진 객체(thenable)에도 await 을 사용가능함
const thenable = {
then: function(resolve) {
setTimeout(() => resolve('완료'), 1000);
}
};
async function example() {
const result = await thenable;
console.log(result); // '완료'
}
3. 비동기 이터레이터(Async Iterators)와 함께 사용
async function* asyncGenerator() {
yield 1;
yield 2;
yield 3;
}
async function example() {
for await (const num of asyncGenerator()) {
console.log(num);
}
}
// 1, 2, 3 순서대로 출력