ํฐ์คํ ๋ฆฌ ๋ทฐ
๋ฌธ์
async/await ๋น๋๊ธฐ ์ฒ๋ฆฌ ํจ์ ๋ด์์ ํน์ ์ ๋ณด๋ค์ด ๋ด๊ธด ์์ดํ ๋ฆฌ์คํธ๋ฅผ ์๋ฒ๋ก๋ถํฐ ์ ๋ฌ ๋ฐ์ ๋ฐํํ๋๋ก ๋ค์๊ณผ ๊ฐ์ด ์ฝ๋๋ฅผ ์์ฑํ์๋ค.
export interface ItemType {
created_at: number;
key: string;
expires_at: number;
download_count: number;
count: number;
size: number;
summary: string;
thumbnailUrl: string;
files: File[];
sent?: Sent;
}
export const getItemData = async (): ItemType[] => {
const { data } = await axios.get('https://romantic-hopper-546d5e.netlify.app/data/itemInfoList.json');
return data;
}
ํ์ง๋ง ์๋ํ ๊ฒฐ๊ณผ๊ฐ ์๋ ๋ค์๊ณผ ๊ฐ์ ํ์ ์ค๋ฅ๊ฐ ๋ฐ์ํ์๋ค.
'ItemType[]' ํ์์ Promise ํธํ ์์ฑ์ ๊ฐ์ ์ฐธ์กฐํ์ง ์์ผ๋ฏ๋ก ES5/ES3์์ ์ ํจํ ๋น๋๊ธฐ ํจ์ ๋ฐํ ํ์์ด ์๋๋๋ค.ts(1055)
๋ฌธ์ ํด๊ฒฐ
async function์ ํญ์ Promise ๊ฐ์ฒด๋ฅผ ๋ฆฌํดํ๊ณ await์์ ์ฝ๋ ์คํ์ ์ผ์ ์ค์งํ๊ณ ํจ์์์ ๋ฐํ๋ Promise ๊ฐ์ฒด์ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ๋ค๋ฆฐ๋ค.
async function์ ํญ์ ๋น๋๊ธฐ ์ฐ์ฐ ๊ณผ์ ์ ๊ฑฐ์น๊ธฐ ๋๋ฌธ์ Promise ๊ฐ์ฒด๋ฅผ ๋ฆฌํดํ๊ธฐ ๋๋ฌธ์ ์ ์ฝ๋์์๋ ์๋ฒ์์ ์ ๋ฌ ๋ฐ์ ๋ฐ์ดํฐ ํ์ ๊ทธ ์์ฒด๋ฅผ ๋ฆฌํด ํ์ ์ผ๋ก ๋ช ์ํด์ฃผ๋ ๊ฒ์ด ์๋๋ผ Promise<F> ํ์ ํ์์ ์ง์ ํด์ค์ผ ๋์๋ค.
export const getItemData = async (): Promise<ItemType[]> => {
const { data } = await axios.get('https://romantic-hopper-546d5e.netlify.app/data/itemInfoList.json');
return data;
}
Reference
https://radlohead.gitbook.io/typescript-deep-dive/future-javascript/async-await
Async Await - TypeScript Deep Dive
wrapToReturnPromise๋ ์ ๋ค๋ ์ดํฐ ํจ์๋ฅผ ์ฌ์ฉํ์ฌ generator ๊ฐ์ฒด๋ฅผ ๋ฐํ๋ฐ์ ๋ค์, generator.next()๋ฅผ ์ฌ์ฉํฉ๋๋ค. ๋ง์ฝ ๊ฐ์ด promise ๋ผ๋ฉด then+catchํ๊ณ ๊ฒฐ๊ณผ๊ฐ์ generator.next(result)๋๋ generator.thorw(error) ๋ก
radlohead.gitbook.io