ES2022-top-level-await&array-at.md
๐กES2022 new features!
๊ด๋ จ๊ธ:
https://www.turing.com/kb/latest-javascript-features-in-es2022
https://dev.to/jasmin/whats-new-in-es2022-1de6
๐ธ 2022๋
6์ ํ์ ๋ ์๋ฐ์คํฌ๋ฆฝํธ ๊ธฐ๋ฅ์
๋๋ค.
- Await operator at the top-level // ์ต์์ await(๋ชจ๋ ๋ด)
- Class field declarations // ์์ฑ์ constructor ์์ ์์ฑํ์ง ์์๋ ๋จ
- Private methods and fields // #์ ๋ถ์ฌ์ private ์ฌ์ฉ
- Static class fields and private static methods // static field ์ฌ์ฉ ๊ฐ๋ฅ
- Regexp Match Indices // ํจํด๊ณผ ์ผ์นํ๋ ๋ฌธ์์ ์ธ๋ฑ์ค๋ฅผ ์ ์ ์์
- Ergonomic brand checks for private fields
- Array.prototype.at() function for Indexing // -1, ๋ง์ด๋์ค ์ธ๋ฑ์ค
- Object.hasOwn() // ์๊ธฐ ์์ ์ ์์ฑ์ธ์ง ํ์ธ => boolean
- Temporal function
- Error Cause // ์๋ฌ ๊ฐ์ฒด์ ์์ธ์ ์ ์ `new Error('', {cause: ''});`
ES2022: top-level await โจ
- top-level await๋ ES2022์์ ๋์จ ๊ธฐ๋ฅ์ด๋ฉฐ, ๋ชจ๋์์๋ง ์ฌ์ฉ ๊ฐ๋ฅํฉ๋๋ค.
- ๋ค์๊ณผ ๊ฐ์ด ์ต์์์์ await๋ฅผ ์ธ ์ ์์ต๋๋ค.
const res = await fetch(`https://jsonplaceholder.typicode.com/posts`);
const data = await res.json();
console.log(data);
โ ๏ธ ์ฃผ์์
- ์ต์๋จ await๋ฅผ ์ฌ์ฉํ๋ฉด promise๊ฐ resolve๋ ๋๊น์ง ํ๋จ ์ฝ๋๋ฅผ blocking ํฉ๋๋ค.
- ๊ธฐ๋ฅ์ ์ ํํ ์๊ณ ์ฌ์ฉํ๋ ๊ฒ์ด ์ค์ํฉ๋๋ค.
- ์ต์๋จ await๋ก ์ธํด ์ฝ๋๊ฐ blocking ๋๋ ์์์
๋๋ค.
-
console.log(lastPostAwait)
๋ ์๋จ์const lastPostAwait = await getLastPost();
๊ฐ resolve๋ ๋๊น์ง ์คํ๋์ง ์์ต๋๋ค.const getLastPost = async () => { const res = await fetch(`https://jsonplaceholder.typicode.com/posts`); const data = await res.json(); return { title: data.at(-1).title, text: data.at(-1).body }; // at() ๋ํ ES2022์ ๊ธฐ๋ฅ์ ๋๋ค. }; const lastPost = getLastPost(); console.log(lastPost); // X, promise is pending lastPost.then((last) => console.log(last)); // X, not clean const lastPostAwait = await getLastPost(); console.log(lastPostAwait); // O, use top-level await
-
- ์ต์์ await์ code blocking ์์
-
์ต์์ await๊ฐ ์๋ ๋ชจ๋์ importํ๋ฉด, importํ ๋ชจ๋์ ๋ถ๋ฌ์จ ๋ชจ๋์ด blocking code๋ฅผ ์๋ฃํ ๋๊น์ง ๊ธฐ๋ค๋ฆฝ๋๋ค.
console.log("Export Linked"); console.log("์์ฒญ ์์"); const res = await fetch(`https://jsonplaceholder.typicode.com/posts`); // resolve๋ ๋๊น์ง ์ฝ๋ blocking const data = await res.json(); // resolve๋ ๋๊น์ง ์ฝ๋ blocking console.log("์์ฒญ ๋"); export const lastData = { title: data.at(-1).title, text: data.at(-1).body }; // await ์์ด๋ ok // console.log(lastData) // ์ด๊ณณ์์๋ ์ ์
import * as FetchUsers from "./fetchUsers.js"; console.log("Import"); console.log("๋ฉ์ธ ๋ชจ๋ ์์"); console.log(FetchUsers.lastData); // link๋ lastData ๊ฐ์ ๊ฐ์ ธ์ต๋๋ค.
-
ES2022: Array.at()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.at
- js์์๋ ํ์ด์ฌ ๋๋ R์ฒ๋ผ array[-1]์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
- bracket ๋ด๋ถ์ ์์ number๋ string์ผ๋ก ๊ฐ์ฃผํฉ๋๋ค. โ array[โ-1โ]
- at์ ์ฌ์ฉํ๋ฉด, -1๋ก ๋ง์ง๋ง ์์๋ฅผ ๊ฐ์ ธ์ฌ ์ ์์ต๋๋ค.
array[array.length - 1]
array.at(-1)
- 88.28% โ ์ผ๋ถ ๋ธ๋ผ์ฐ์ ์์ ํธํ๋์ง ์์ต๋๋ค.