๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’๊ณต๋ถ€/JS

[JavaScript] Callback vs Promise vs async-await

by rindev 2021. 10. 10.

promise๋Š” ์ด์ œ ์ง„์งœ ์•Œ ๋•Œ๋„ ๋˜์—ˆ๋‹ค. #๊ฐ€๋ณด์ž๊ณ ...

 

โœ… Callback

์ฝ”๋“œ ์ถœ์ฒ˜ : https://librewiki.net/wiki/%EC%BD%9C%EB%B0%B1_%EC%A7%80%EC%98%A5

  • ์ฝœ๋ฐฑ ์ง€์˜ฅ = ์ฝœ๋ฐฑ์ด ๋„ˆ๋ฌด ๊ธธ์–ด์ง€๋ฉด ์ฝ๊ธฐ ํž˜๋“ค๊ณ , ์ดํ•ดํ•˜๊ธฐ๋„ ํž˜๋“ฌ
  • ์—๋Ÿฌ์ฒ˜๋ฆฌํ•˜๊ธฐ๋„ ํž˜๋“ฌ
  • ์œ ์ง€๋ณด์ˆ˜๋„ ํž˜๋“ฌ
  • ๊ทธ๋ฆฌ๊ณ  ์‹คํŒจํ–ˆ๋Š”์ง€/์„ฑ๊ณตํ–ˆ๋Š”์ง€/๋Œ€๊ธฐ์ค‘์ธ์ง€ ์•Œ๋ ค์ฃผ์ง€ ์•Š์Œ (์—๋Ÿฌ๊ฐ€ ๋‚˜์•ผ๋งŒ ์•„ ๋ญ”๊ฐ€ ์ž˜๋ชป๋๊ตฌ๋‚˜ ๋ผ๊ณ  ์•Œ์ˆ˜์žˆ์Œ๐Ÿ˜ฐ)

→ ๊ทธ๋ž˜์„œ promise๊ฐ€ ๋“ฑ์žฅ

 

โœ… Promise 

  • promise๋Š” ๊ฐ์ฒด์ž„
  • new Promise()๋กœ ํ”„๋กœ๋ฏธ์Šค๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ์ข…๋ฃŒํ•  ๋•Œ ๊นŒ์ง€ ํ”„๋กœ๋ฏธ์Šค๋Š” 3๊ฐ€์ง€ ์ƒํƒœ๋ฅผ ๊ฐ€์ง
    • pending(๋Œ€๊ธฐ) : ๋น„๋™๊ธฐ์ฒ˜๋ฆฌ ๋ฏธ์™„๋ฃŒ (์ƒ์„ฑ ์งํ›„ === ๊ธฐ๋ณธ์ƒํƒœ)
    • fulfilled(์ดํ–‰) : ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ์„ฑ๊ณต → resolve ํ˜ธ์ถœ
    • rejected(์‹คํŒจ) : ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ์‹คํŒจ → reject ํ˜ธ์ถœ
  • Promise ํ›„์† ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ
    • then : ์ธ์ž๋ฅผ 2๊ฐœ ๋ฐ›์„ ์ˆ˜ ์žˆ์Œ (1๋ฒˆ์งธ = ์„ฑ๊ณต ์‹œ ํ˜ธ์ถœ, 2๋ฒˆ์งธ = ์‹คํŒจ ์‹œ ํ˜ธ์ถœ) → promise ๊ฐ์ฒด return
    • catch : ์‹คํŒจํ–ˆ์„ ๋•Œ์—๋งŒ ํ˜ธ์ถœ ๋จ, then์˜ 2๋ฒˆ์žฌ ์ธ์ž์™€ ๊ฐ™์€ ์—ญํ• ์„ ํ•จ → promise ๊ฐ์ฒด return
    • finally : ์„ฑ๊ณต/์‹คํŒจ ์—ฌ๋ถ€์™€ ์ƒ๊ด€ ์—†์ด ๋ฌด์กฐ๊ฑด ๋”ฑ!! ํ•œ๋ฒˆ๋งŒ!! ํ˜ธ์ถœ๋จ

 

โœ… async-await

promise๋ฅผ ์กฐ๊ธˆ ๋” ์ข‹๊ฒŒ ๋งŒ๋“ฌ!

// promise ์—ฐ์† ํ˜ธ์ถœ
function getData() {
    return promise1()
        .then(response => {
            return response;
        })
        .then(response2 => {
            return response2;
        })
        .catch(err => {
            //TODO: error handling
            // ์—๋Ÿฌ๊ฐ€ ์–ด๋””์„œ ๋ฐœ์ƒํ–ˆ๋Š”์ง€ ์•Œ๊ธฐ ์–ด๋ ต๋‹ค.
        });
}

// async await ์—ฐ์† ํ˜ธ์ถœ
async function getData() {
    const response = await promise1();
    const response2 = await promise2(response);
    return response2;
}

์ฝ”๋“œ ์ถœ์ฒ˜ : https://ithub.tistory.com/223

  • ์ฝ”๋“œ๊ฐ€ ๋น„๊ต์  ๊ฐ„๊ฒฐํ•˜๊ณ , ๊ฐ€๋…์„ฑ์ด ๋†’์•„์ง
  • ์‘๋‹ต ๋ฐ์ดํ„ฐ๋กœ ๋“ค์–ด์˜ค๋Š” ๋ณ€์ˆ˜(์ฃผ๋กœ res, response, data ๋“ฑ๋“ฑ์œผ๋กœ ์“ฐ์ด๋Š” ์• ๋“ค)๋ฅผ ์—†์•จ ์ˆ˜ ์žˆ๋‹ค
  • try-catch๋กœ ์—๋Ÿฌ๋ฅผ ํ•ธ๋“ค๋งํ•จ
  • error๊ฐ€ ์–ด๋””์„œ ๋ฐœ์ƒํ–ˆ๋Š”์ง€ ์•Œ๊ธฐ ์‰ฌ์›€ 

 

 

๐Ÿ‘€์ฐธ๊ณ  (๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค)

๋”๋ณด๊ธฐ

 

๋Œ“๊ธ€