[JavaScript] async & await

ํ˜œ๋ฆฐยท2022๋…„ 6์›” 27์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
13/21
post-thumbnail

๐Ÿ“ async์™€ await์„ ์‚ฌ์šฉํ•˜์—ฌ ์ง๊ด€์ ์œผ๋กœ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด๋ณด์ž


async


๐Ÿ“ async๋ž€

async๋Š” Promise๋ฅผ ๋” ์‰ฝ๊ฒŒ ์ด์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋„์™€์ค€๋‹ค.
ํ•จ์ˆ˜ ์•ž์— async๋ฅผ ๋ถ™์ด๋ฉด ํ•ด๋‹น ํ•จ์ˆ˜๋Š” Promise๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋น„๋™๊ธฐ์ฒ˜๋ฆฌ ํ•จ์ˆ˜๊ฐ€ ๋œ๋‹ค.

๐Ÿ“ ์‚ฌ์šฉ ์˜ˆ์ œ

function hello(){
	return "hello";
}

async function helloAsync(){
	return "hello Async";
}

console.log(hello()); // hello
console.log(helloAsync()); // Promise{<pending>}

helloAsync ํ•จ์ˆ˜ ์•ž์— async๊ฐ€ ๋ถ™์—ฌ์ ธ ์žˆ์–ด, Promise๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์žˆ๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋ ‡๋‹ค๋ฉด ์ด์ œ helloAsync ํ•จ์ˆ˜์— then์„ ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

helloAsync().then((res) => {
	console.log(res);
}); // hello Async

async๋ฅผ ๋ถ™์—ฌ์ค€ helloAsync ํ•จ์ˆ˜์˜ return ๊ฐ’์€ Promise์˜ resolve ๊ฒฐ๊ณผ๊ฐ’์ด ๋œ๋‹ค.


await


๐Ÿ“ await์ด๋ž€

await์€ async ํ•จ์ˆ˜ ์•ˆ์—์„œ๋งŒ ๋™์ž‘ํ•˜๋ฉฐ,
JavaScript๋Š” await์„ ๋งŒ๋‚˜๋ฉด Promise๊ฐ€ ์ฒ˜๋ฆฌ๋  ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆฐ๋‹ค.

๐Ÿ“ ์‚ฌ์šฉ ์˜ˆ์ œ

// function delay(ms){
// 	return new Promise((resolve) => {
// 		setTimeout(() => {
// 			resolve();
//		}, ms);
//	});
//}

function delay(ms){
	return new Promise((resolve) => {
		setTimeout(resolve, ms);
	});
}

1. delay()ํ•จ์ˆ˜ ์ƒ์„ฑ

  • ์ „๋‹ฌ๋ฐ›์€ ms๋งŒํผ setTimeout์ด ๋Œ€๊ธฐํ–ˆ๋‹ค๊ฐ€, resolveํ•˜๋ฉฐ ๋๋‚˜๋Š” delay ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค.
  • setTimeout์ด resolveํ•˜๋Š” ๊ฒƒ ๋ฐ–์— ์—†์œผ๋ฏ€๋กœ ์ฝœ๋ฐฑํ•จ์ˆ˜ ์ž์ฒด๋ฅผ resolve๋กœ ์ „๋‹ฌํ•˜๋Š” ์•„๋ž˜์˜ ํ˜•ํƒœ๋กœ ๊ฐ„์ถ”๋ฆด ์ˆ˜ ์žˆ๋‹ค.
// async function helloAsync(){
// 	return delay(3000).then(() => {
// 		return "hello Async";
// 	});
// }

async function helloAsync(){
	await delay(3000);
	return "hello async";
}

helloAsync.then((res) => {
	console.log(res);
});

// 3์ดˆ๋’ค, hello Async ์ถœ๋ ฅ๋จ

2. await ์‚ฌ์šฉ

  • await์„ ์‚ฌ์šฉํ•˜์—ฌ return์„ 2๋ฒˆํ•˜๊ณ  ์žˆ๋Š” helloAsync()๋ฅผ ๊ฐ„๋‹จํ•˜๊ฒŒ ๋ฐ”๊พธ์–ด๋ณผ ์ˆ˜ ์žˆ๋‹ค.
  • await์„ ๋น„๋™๊ธฐ ํ•จ์ˆ˜ ํ˜ธ์ถœ ์•ž์— ๋ถ™์ด๋ฉด ๋น„๋™๊ธฐ ํ•จ์ˆ˜๊ฐ€ ๋งˆ์น˜ ๋™๊ธฐ์ ์ธ ํ•จ์ˆ˜์ฒ˜๋Ÿผ ์ž‘๋™ํ•œ๋‹ค.
  • await์ด ๋ถ™์€ ํ•จ์ˆ˜์˜ ํ˜ธ์ถœ์€ ๋’ค์— ์žˆ๋Š” ํ•จ์ˆ˜๊ฐ€ ๋๋‚˜๊ธฐ ์ „๊นŒ์ง€ ์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ ์ˆ˜ํ–‰ํ•˜์ง€ ์•Š๋Š”๋‹ค.



์ฐธ๊ณ 


ํ•œ์ž… ํฌ๊ธฐ๋กœ ์ž˜๋ผ ๋จน๋Š” ๋ฆฌ์•กํŠธ๋ฅผ ํ•™์Šตํ•˜๋ฉฐ ๊ฐœ์ธ์ ์œผ๋กœ ์ •๋ฆฌํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค.

profile
FE Developer

0๊ฐœ์˜ ๋Œ“๊ธ€