JavaScript Promise

Promise

  • promise: ๋น„๋™๊ธฐ๋ฅผ ๊ฐ„ํŽธํ•˜๊ฒŒ ์ฒ˜๋ฆฌ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” object

  • ์ •ํ•ด์ง„ ์žฅ์‹œ๊ฐ„์˜ ๊ธฐ๋Šฅ์„ ์ˆ˜ํ–‰ํ•˜๊ณ  ์„ฑ๊ณตํ•ด์ง„ ๋ฉ”์„ธ์ง€์™€ ํ•จ๊ป˜ ๊ธฐ๋Šฅ ์ˆ˜ํ–‰ ์•„๋‹ˆ๋ฉด ์—๋Ÿฌ๊ฐ€ ๋œธ

Producer

// Promise is a JavaScript object for asynchronous peration
// state (์ƒํƒœ):pending -> fulfilled or rejected 
// producer vs cosumer ๋งŒ๋“œ๋Š”์‚ฌ๋žŒ/ ์†Œ๋น„ํ•˜๋Š”์‚ฌ๋žŒ

const promise = new Promise((resolve, reject) => {
// when new Promise is created, the ececutor runs automatically.
//doing some heavy work (network, read files)
// ์ฝ์–ด์˜ค๋Š”๊ฒƒ, ๋„คํŠธ์›Œํฌ ์ด๋Ÿฐ๊ฒƒ๋“ค์€ ๋ฌด๊ฒ๊ธฐ๋•Œ๋ฌธ์— ๋น„๋™๊ธฐ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š”๊ฒƒ์ด ์ข‹๋‹ค
// promise๊ฐ€ ๋งŒ๋“ค์–ด์ง„ ์ˆœ๊ฐ„ ๋ฐ”๋กœ ์ˆ˜ํ–‰์„ ํ•˜๊ฒŒ๋จ
// ์‚ฌ์šฉ์ž๊ฐ€ ๋ฒ„ํŠผ์„ ๋ˆŒ๋ €์„๋•Œ ๋„คํŠธ์›Œํฌ๊ฐ€ ์ž‘๋™๋˜๊ฒŒ ํ•˜๋Š”๊ฒƒ์€ ๋ฐ”๋กœ ์ˆ˜ํ–‰๋˜๊ธฐ๋•Œ๋ฌธ์— ๋งž์ง€์•Š์Œ 
    console.log('doing something...');
    setTimeout(() => {
       resolve('ellie')
     //reject(new Error('no network'));
    }, 2000);
});

consumers : then, catch, finally

promise chaining

Error Handling

์ฝœ๋ฐฑ์ง€์˜ฅ ์ฝ”๋“œ์ˆ˜์ •

Last updated

Was this helpful?