ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๋ฌธ์ œ

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

 

๋Œ“๊ธ€
๊ณต์ง€์‚ฌํ•ญ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
Total
Today
Yesterday
๋งํฌ
TAG
more
ยซ   2024/07   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
๊ธ€ ๋ณด๊ด€ํ•จ