Async... Await...
async function
์๋ฐ์คํฌ๋ฆฝํธ๋ ๊ธฐ๋ณธ์ ์ผ๋ก ๋๊ธฐ์ ์ผ๋ก ์คํ๋๋ ์ธ์ด๋ค.
์ด๋ ์ฝ๋๊ฐ ์์ฑ๋ ์์๋๋ก ํ ์ค์ฉ ์คํ๋๋ฉฐ, ๊ฐ ๋ผ์ธ์ ์ฝ๋๊ฐ ์๋ฃ๋๊ธฐ ์ ๊น์ง๋ ๋ค์ ๋ผ์ธ์ผ๋ก ๋์ด๊ฐ์ง ์๋๋ค๋ ๊ฒ์ ์๋ฏธํ๋ค.
์ด๋ฌํ ๋๊ธฐ์ ์คํ ๋ชจ๋ธ์ ์ฝ๋์ ํ๋ฆ์ ์์ธกํ๊ธฐ ์ฝ๊ฒ ํ์ฃผ์ง๋ง, ์ค๋ ๊ฑธ๋ฆฌ๋ ์์ (์: ๋คํธ์ํฌ ์์ฒญ)์ ์ฒ๋ฆฌํ ๋ ๋ฌธ์ ๊ฐ ๋ฐ์ํ ์ ์๋ค.
async
์await
์ ์๋ฐ์คํฌ๋ฆฝํธ์์ ๋น๋๊ธฐ ์์ ์ ๋ ํธ๋ฆฌํ๊ฒ ๋ค๋ฃจ๊ธฐ ์ํด ์ฌ์ฉ๋๋ ํค์๋๋ค.
async
์ด ํค์๋๋ ๋น๋๊ธฐ ํจ์๋ฅผ ์ ์ธํ๋ ๋ฐ ์ฌ์ฉ๋๋ค.
async
ํจ์๋Promise
๋ฅผ ๋ฐํํ๋ค.์๋ฒ์์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋ ๋ฑ์ ์๊ฐ์ด ๊ฑธ๋ฆฌ๋ ์์ ์ ์ํํ๋ ํจ์๊ฐ ์์ ๋ async๋ฅผ ์ ์ธํ๊ณ ์ฌ์ฉํ๋ค.
์๋ฐ์คํฌ๋ฆฝํธ์๊ฒ ์ด ํจ์๋ฅผ ๋น๋๊ธฐ์ ์ผ๋ก ์ฒ๋ฆฌํ๋ผ๊ณ ์๋ ค์ค๋ค
async function fetchData() {
// API์์ ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ
}
await
์ด ํค์๋๋
async
ํจ์ ๋ด์์Promise
๊ฐ ํด๊ฒฐ๋ ๋๊น์ง ๊ธฐ๋ค๋ฆฌ๋ ๋ฐ ์ฌ์ฉ๋๋ค.ํจ์์ ์คํ์
Promise
๊ฐ ์ฒ๋ฆฌ๋ ๋๊น์ง(์ดํ๋๊ฑฐ๋ ๊ฑฐ๋ถ๋ ๋๊น์ง) ์ผ์ ์ค์งํ๋ค.await
๋ ์ค์งasync
ํจ์ ๋ด์์๋ง ์ฌ์ฉํ ์ ์๋ค.
async function fetchData() {
let data = await fetch('https://api.example.com/data');
let jsonData = await data.json();
return jsonData;
}
์์
await
์ฌ์ฉํ๋ ๊ฒฝ์ฐ
function resolveAfter2Seconds() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('resolved');
console.log('promise');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// Expected output:
// > "calling"
// > "promise"
// > "resolved"
}
asyncCall();
await
์ฌ์ฉํ์ง ์๋ ๊ฒฝ์ฐ
function resolveAfter2Seconds() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('resolved');
console.log('promise');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = resolveAfter2Seconds();
console.log(result);
// Expected output:
// > "calling"
// > [object Promise] >
// "promise"`
asyncCall();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Last updated
Was this helpful?