Top-level await enables modules to act as big async functions
ES2022에서 나온 기능으로 모듈의 최상위 스코프에서 비동기 동작을 await하여 사용할 수 있다.
이전에는 async 키워드가 있는 스코프 내에서만 await를 통해 해당 스코프에서 비동기 동작이 완료되기까지 블로킹할 수 있었는데
모듈단위에서 await를 통해 특정 비동기 함수의 동작이 완료되기까지 하위 모듈의 동작을 막을 수 있다.
//a.js
import fetch from "node-fetch";
let users;
export default (async () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/users');
users = resp.json();
})();
export { users };
//b.js
import promise, {users} from './a.js';
promise.then(() => {
console.log('All users:', users);
});
a 모듈을 b 모듈에서 사용할 때 a 모듈의 비동기 처리가 완료된 후 사용을 보장하기 위해 위와 같이 해야했던 처리를
//a.js
const resp = await fetch('https://jsonplaceholder.typicode.com/users');
const users = resp.json();
export { users};
//b.js
import { users } from './a.js';
console.log(users);
console.log('In usingAwait module');
이렇게 보다 간결하게 처리할 수 있다.
Loading modules dynamically
const strings = await import(`/i18n/${navigator.language}`);
Resource Initialization
const connection = await dbConnector();
Dependency fallback
let translations;
try {
translations = await import('https://app.fr.json');
} catch {
translations = await import('https://fallback.en.json');
}
tsconfig
컴파일 옵션에서target
자바스크립트 버전을 최소 es2017
로 맞춰주면 사용할 수 있다.
target option
TypeScript 컴파일러가 생성하는 JavaScript 코드의 목표 버전을 지정
{
"compilerOptions": {
"target": "es2017",
// ...
},
}
async/await
가 es2017에서 나와서 최소 es2017버전으로 컴파일 해야 적용이 되는건가 생각이 된다.