๐ง ๋น๋๊ธฐ๋ฅผ ๋ค๋ฃจ๋ ๋ ๋ค๋ฅธ ๋ฐฉ๋ฒ
๐ง ํจ์ ์ด๋ฆ ์์ async๋ฅผ ๋ถ์ด๊ฑฐ๋, ํ์ดํ ํจ์ ์์ async๋ฅผ ๋ถ์ด๋ ๋ฐฉ์์ผ๋ก ์ฌ์ฉํ๋ค.
async function ํจ์์ด๋ฆ() { }
const ํจ์์ด๋ฆ = async() => { }
๐ง Async-Await ํจ์๋ Promise๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ํ๊ณ ์๋ค.
function p(ms){
return new promise((resolve,reject)=>{
setTimeout(()=>{
resolve(ms);
},ms);
});
}
//1. Promise ๊ฐ์ฒด๋ฅผ ์ด์ฉํด์ ๋น๋๊ธฐ ๋ก์ง์ ์ํํ ๋
p(1000).then((ms) => {
console.log(`${ms}ms ํ์ ์คํ๋๋ค.`);
});
//2. Promise ๊ฐ์ฒด๋ฅผ ๋ฆฌํดํ๋ ํจ์๋ฅผ await๋ก ํธ์ถํ๋ ๋ฐฉ๋ฒ
const ms = await p(1000);
console.log(`${ms}ms ํ์ ์คํ๋๋ค.`);
// ๐จ error : SyntaxError: await is only valid in async function
// await์ ์ฌ์ฉํ๋ ค๋ฉด ํญ์ async ํจ์ ์์์ ์ฌ์ฉ๋์ด์ผ ํ๋ค.
โญ๏ธ ํจ์ ์์๋
async
, ํ๋ก๋ฏธ์ค ์์๋await
์ ๋ถ์ฌ์ค๋ค.
โจ await, async ์ฅ์ : ๋ก์ง์ ์ฝ๋๊ฐ ๋ฐ์ผ๋ก ๋ด๋ ค๊ฐ ์ ์๊ฒ ํํํ ์ ์์ด์ ์์๋ณด๊ธฐ ํธํ๋ค.
function p(ms){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(ms);
},ms);
});
}
//Promise ๊ฐ์ฒด๋ฅผ ๋ฆฌํดํ๋ ํจ์๋ฅผ await๋ก ํธ์ถํ๋ ๋ฐฉ๋ฒ
(async function main(){
const ms = await p(1000);
console.log(`${ms}ms ํ์ ์คํ๋๋ค.`);
})();
function p(ms){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
reject(new Error('reason'));
},ms);
});
}
(async function main(){
try{
const ms = await p(1000);
} catch(error){
console.log(error);
}
})();
async function asyncP(){
return 'doyeon';
}
(async function main(){
try{
const name = await asyncP();
console.log(name);
} catch(error){
console.log(error);
}
})();
function p(ms){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(ms);
// reject(new Error('reason'));
},ms);
});
}
async function asyncP(){
// ๋ง์ฝ p์์ reject๊ฐ ๋๋ฉด, asyncP์์ try,catch๋ฌธ์ผ๋ก ์๋ฌ์ฒ๋ฆฌ๋ฅผ ํด์ฃผ๋ฉด ๋๋ค.
const ms = await p(1000);
return 'doyeon:' + ms;
// 1์ด ํ์ doyeon 1000 ์ด ์ถ๋ ฅ๋๋ค.
}
(async function main(){
try{
const name = await asyncP();
console.log(name);
} catch(error){
console.log(error);
} finally {
console.log('resolve ๋๊ฑฐ๋ reject ๋ ํ์ end');
}
})();
function p(ms){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(ms);
//reject(new Error('reason'));
},ms);
});
}
// Promise : ๊ณ์ ๋ง๋ค์ด์ return, chaining
p(1000)
.then(()=> p(1000)
.then(()=> p(1000))
.then(()=>{
console.log('3000ms ํ์ ๋ฐ์');
}));
// Async : ํ์คํ์ค์ด ๋๋์ผ ๋น๋๊ธฐ๊ฐ ์งํ๋จ
(async function main(){
await p(1000);
await p(1000);
await p(1000);
console.log('3000ms ํ์ ๋ฐ์');
})();
function p(ms){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(ms);
//reject(new Error('reason'));
},ms);
});
}
(async function main() {
const results = await Promise.all([p(1000),p(2000),p(3000)]);
// ์ถ๋ ฅ: 3์ดํ์ [1000,2000,3000]
console.log(results);
})();
(async function main() {
const result = await Promise.race([p(1000),p(2000),p(3000)]);
// ์ถ๋ ฅ: 1์ดํ์ 1000
console.log(result);
})();