async
- promise 가 실행된다. / then, catch 사용 가능
async function getName() {
return "Mike"
}
get Name().then((name) => {
console.log(name); // Mike 가 출력
})
async function getName() {
throw new Error("err...");
}
getName().catch((err)=> {
console.log(err); // catch 사용하여 err 출력
})
await
function getName(name) {
return new Promise((resolve, reject)=> {
setTimeout(()=> {
resolve(name);
},1000);
});
}
async function showName() {
const result = awaot getName("Mike");
console.log(result);
}
console.log("시작");
showName(); // 시작 -> mike 순으로 출력
예제코드
- promise 를 이용했던 코드를 async/ await로 바꾸어 보았다.
const f1 = () => {
return new Promise((res, rej)=> {
setTImeout(()=>{
res("1번 주문 완료);
}, 1000)
});
};
const f2 = (message) => {
console.log("message");
return new Promise((res, rej)=> {
setTImeout(()=>{
res("2번 주문 완료);
}, 3000)
});
};
const f3 = (message) => {
console.log(message);
return new Promise((res, rej)=> {
setTImeout(()=>{
res("3번 주문 완료);
}, 2000)
});
};
f1()
.then((res) => f2(res))
.then((res) => f3(res))
.then((res) => console.log(res))
.catch(console.log) // promis then/catch를 이용한 코드
async function order() {
const result1 = await f1();
const result2 = await f2(reuslt1);
const result3 = await f3(result2);
console.log (result3);
console.log("종료");
} // async , await 로 바꾼 코드
* catch 문을 이용하고 싶은 이유
async function order() {
try{
const result1 = await f1();
const result2 = await f2(reuslt1);
const result3 = await f3(result2);
console.log (result3);
} catch(e){
console.log(e);
}
console.log("종료");
} // try catch문으로 감싸면 err코드를 잡을 수 있다 .
order();