๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

JavaScript

[ JavaScript ] async await ๋ฌธ๋ฒ•

 

 

 

ES8์—์„œ ๊ฐ„๋‹จํ•˜๊ณ  ๊ฐ€๋…์„ฑ ์ข‹๊ฒŒ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ๋ฅผ ๋™๊ธฐ์ฒ˜๋Ÿผ ๋™์ž‘ํ•˜๋„๋ก ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” async/await๊ฐ€ ๋“ฑ์žฅํ–ˆ๋‹ค.

async/await๋Š” ํ”„๋กœ๋ฏธ์Šค๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋™์ž‘ํ•˜๋ฉฐ, async/await๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ”„๋กœ๋ฏธ์Šค์˜ ํ›„์† ์ฒ˜๋ฆฌ ๋ฉ”์„œ๋“œ ์—†์ด ๋งˆ์น˜ ๋™๊ธฐ ์ฒ˜๋ฆฌ์ฒ˜๋Ÿผ ํ”„๋กœ๋ฏธ์Šค๊ฐ€ ์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

async ํ•จ์ˆ˜๋Š” async ํ‚ค์›Œ๋“œ๋ฅผ ํ†ตํ•ด ์ •์˜ํ•˜๊ณ , ํ”„๋กœ๋ฏธ์Šค๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();

await ํ‚ค์›Œ๋“œ๋Š” ํ”„๋กœ๋ฏธ์Šค๊ฐ€ settled ์ƒํƒœ(๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ๊ฐ€ ์ˆ˜ํ–‰๋œ ์ƒํƒœ)๊ฐ€ ๋  ๋•Œ๊นŒ์ง€ ๋Œ€๊ธฐํ•˜๋‹ค๊ฐ€ settled ์ƒํƒœ๊ฐ€ ๋˜๋ฉด ํ”„๋กœ๋ฏธ์Šค์˜ resolve r๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. await ํ‚ค์›Œ๋“œ๋Š” async ํ•จ์ˆ˜์—์„œ๋งŒ ์œ ํšจํ•˜๊ณ , async ํ•จ์ˆ˜ ์™ธ๋ถ€์—์„œ ์‚ฌ์šฉํ•˜๋ฉด SyntaxError๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

 

 

await๋ฌธ์ด ์žˆ๋‹ค๋ฉด asynct ํ•จ์ˆ˜๋Š” ๋น„๋™๊ธฐ์ ์œผ๋กœ ์™„๋ฃŒ๋˜๊ธฐ ๋•Œ๋ฌธ์— ๋ชจ๋“  ํ”„๋กœ๋ฏธ์Šค์— await ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ์ฃผ์˜ํ•˜์—ฌ์•ผ ํ•œ๋‹ค.

async function getFruit(){
	const apple = await new Promise(resolve => setTimeout(() => resolve('apple'), 2000));
	const banana = await new Promise(resolve => setTimeout(() => resolve('banana'), 3000));
	const melon = await new Promise(resolve => setTimeout(() => resolve('melon'), 1000));

	console.log([apple, banana, melon]); // ['apple','banana','melon']
}

getFruit(); // ์•ฝ 6์ดˆ๊ฐ€ ์†Œ์š”๋œ๋‹ค.

 ์œ„์˜ ์˜ˆ์ œ์™€ ๊ฐ™์ด getFruit ํ•จ์ˆ˜๋Š” ์ข…๋ฃŒ๋  ๋•Œ๊นŒ์ง€ ์•ฝ 6์ดˆ๊ฐ€ ์†Œ์š”๋œ๋‹ค. ๊ทธ๋ž˜์„œ ์œ„์™€ ๊ฐ™์ด getFruit ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ 3๊ฐœ์˜ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ๋Š” ์„œ๋กœ ์—ฐ๊ด€์„ฑ์ด ์—†๊ธฐ ๋•Œ๋ฌธ์— apple -> banana -> melon ์‹์˜ ์ˆœ์„œ๋กœ ์ฒ˜๋ฆฌํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.

async function getFruit() {
	const fruits = await Promise.all([
    	new Promise(resolve => setTimeout(() => resolve('apple'), 2000)),
        new Promise(resolve => setTimeout(() => resolve('banana'), 3000)),
        new Promise(resolve => setTimeout(() => resolve('melon'), 1000)),
    ]);
    
    console.log(fruits); // ['apple', 'banana', 'melon']
}

getFruit(); // ์•ฝ 3์ดˆ ์†Œ์š”

์œ„์ฒ˜๋Ÿผ Promise.all ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ”„๋กœ๋ฏธ์Šค์˜ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ›๋Š”๋‹ค.

 

 

 

async/await ์˜ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋Š” try... catch๋ฌธ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.  async ํ•จ์ˆ˜ ๋‚ด์—์„œ catch ๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ์—๋Ÿฌ๋ฅผ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด async ํ•จ์ˆ˜๋Š” ๋ฐœ์ƒํ•œ ์—๋Ÿฌ๋ฅผ reject ํ•˜๋Š” ํ”„๋กœ๋ฏธ์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. 

 

 

 


 

๐ŸŒธ ์ถœ์ฒ˜ ๐ŸŒธ

 

async await- MDN

์ œ๋„ˆ๋ ˆ์ดํ„ฐ์™€ async/await - ๋ชจ๋˜ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๋”ฅ ๋‹ค์ด๋ธŒ

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ 13. ๋น„๋™๊ธฐ์˜ ๊ฝƒ async์™€ await - ๋“œ๋ฆผ์ฝ”๋”ฉ

Promise.all() - MDN