๐ก async ? await ?
- ES2017์ ๋์ ๋ ๋น๋๊ธฐ ์ฒ๋ฆฌ ๋ฌธ๋ฒ
- Promise ๋ก์ง์ ๋ ์ฝ๊ณ ๊ฐ๊ฒฐํ๊ฒ ์ฌ์ฉํ ์ ์๊ฒ ๋์์ค๋ค.
- Promise๋ฅผ ๋์ฒดํ๋ ๊ธฐ๋ฅ์ ์๋๊ณ ๋ณด์ด๋ ๋ฌธ๋ฒ์ ๋ค๋ฅด๊ฒ ํ์ฌ ๊ฐ๋ ์ฑ์ ๋ํ๊ณ ์ ์ง๋ณด์๊ฐ ํธ๋ฆฌํ๊ฒ๋ ๋ง๋ ๋ฌธ๋ฒ
โ ์ฌ์ฉ๋ฒ
function ํค์๋ ์์ async / ๋น๋๊ธฐ ์ฒ๋ฆฌ ์์ await ๋ฅผ ๋ถ์ฌ ์ฌ์ฉํ๋ค.
1) async
- async๋ฅผ ๋ถ์ธ ํจ์๋ promise๋ฅผ ๋ฆฌํดํ๋ ๋น๋๊ธฐ ํจ์๊ฐ ๋๋ค.
- async๋ฅผ ๋ถ์ธ ํจ์์ return ๊ฐ์ promise์ resolve ํจ์์ argument์ ๊ฐ๋ค.
/* ํจ์ ์ ์ธ์ */
async function helloAsync() {
return 'hello Async'
}
/* ํจ์ ํํ์ */
const helloAsync2 = async () => {
return 'hello Async2'
}
2) await
- await์ ๋น๋๊ธฐ ํจ์ ์์ ์์ฑํ๋ค.
- await์ ์์ฑํ๋ฉด ๋น๋๊ธฐ ํจ์๋ฅผ ๋๊ธฐ์ฒ๋ผ ์๋ํ๊ฒ ํ ์ ์๋ค. (์์ฐจ์ ์ผ๋ก)
- await์ async ํจ์ ๋ด์์๋ง ์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
async function main() {
const res = await helloAsync();
const res2 = await helloAsync2();
console.log(res, res2);
}
main(); // 'hello Async hello Async2'
โ ์์
์์ ํฌ์คํ ํ Promise ๊ฒ์๊ธ์ ์์๋ฅผ async await๋ฅผ ์ฌ์ฉํ์ฌ ์ ๋ฆฌํด๋ณด์.
2024.02.15 - [Frontend/Javascript] - [Javascript] ์ฝ๋ฐฑ ์ง์ฅ ํ์ถํ๊ธฐ - Promise
[Javascript] ์ฝ๋ฐฑ ์ง์ฅ ํ์ถํ๊ธฐ - Promise
๐ก ์ฝ๋ฐฑ ์ง์ฅ (Callback Hell) ? ์๋ฐ์คํฌ๋ฆฝํธ๋ ๋น๋๊ธฐ ์์ ์ ์ฒ๋ฆฌํ ๋, ์ฝ๋ฐฑ ํจ์๋ฅผ ์ฌ์ฉํ๋ค. ๋ง์ฝ, ๋น๋๊ธฐ ์์ ์ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ์ง๊ณ ์ฝ๋ฐฑ ๋ด๋ถ์์ ๋๋ค๋ฅธ ์ฝ๋ฐฑ ํจ์๋ฅผ ์ฌ์ฉํ๋ค๋ฉด ์ด๋ป๊ฒ ๋ ๊น?
oneyenee.tistory.com
1) Promise ๋ฐฉ์
function promiseA(a, b) {
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve(a+b) }, 3000)
})
}
function promiseB(a) {
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve(a*2) }, 1000)
})
}
function promiseC(a) {
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve(a*-1) }, 2000)
})
}
promiseA(3,5)
.then((a_res)=>{
console.log('A ํจ์์ ๊ฒฐ๊ณผ ๊ฐ : ', a_res);
return promiseB(a_res);
})
.then((b_res)=>{
console.log('B ํจ์์ ๊ฒฐ๊ณผ ๊ฐ : ', b_res);
return promiseC(b_res);
})
.then((c_res)=>{
console.log('C ํจ์์ ๊ฒฐ๊ณผ ๊ฐ : ', c_res);
})
2) async await ๋ฐฉ์
const delay = async (ms) => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
};
const asyncA = async (a, b, ms) => {
await delay(ms);
return a + b;
};
const asyncB = async (a, ms) => {
await delay(ms);
return a * 2;
};
const asyncC = async (a, ms) => {
await delay(ms);
return a * -1;
};
async function main() {
const a_res = await asyncA(3, 5, 3000);
console.log(a_res);
const b_res = await asyncB(a_res, 1000);
console.log(b_res);
const c_res = await asyncC(b_res, 2000);
console.log(c_res);
}
main();
์ฝ์ ์ฐ๋ ๋ถ๋ถ์ ์ ์ธํ๊ณ ๋ณด๋ฉด promise๋ก .then์ ์ด๊ฑฐํ๋ ๋ฐฉ์๋ณด๋ค ํจ์ฌ ๊ฐ๋ ์ฑ์ด ์ข์์ง ๊ฒ์ ๋ณผ ์ ์๋ค.