정확한 뜻도 모르고 남발했던 async, await ..
이전 글인 axios 정리 중 동기, 비동기의 개념을 제대로 잡아야겠다 결심했습니다! 🧐🧐🧐
(참고: https://private.tistory.com/24)
(참고: https://elvanov.com/2597)
+) 콜백 함수: 함수의 인자로 들어가는 함수
-> https://www.hanumoka.net/2018/10/24/javascript-20181024-javascript-callback/
const p1 = new Promise((resolve, reject) => {
// 비동기 작업
});
new Promise(...
하는 순간 할당된 비동기 작업 바로 시작됨const p1 = new Promise((resolve, reject) => {
// resolve(); 넣으면 then! 나옴
// reject(); 넣으면 catch! 나옴
});
promise1
.then(()=>{
console.log("then!");
})
.catch(()=>{
console.log("catch!");
});
(📍 이해에 많이 도움이 된 사진 한 장 같이 퍼와서 첨부해둡니당)
(참고: https://joshua1988.github.io/web-development/javascript/js-async-await/)
function startAsync(age){
return new Promise((resolve, reject)=>{
if(age>20) resolve('success');
else reject(new Error('wrong');
});
}
////////////////// 같은 의미 //////////////////
async function startAsync(age){
if(age>20) return 'success';
else throw new Error('wrong');
}
await [[Promise 객체]]
Promise 완료될 때까지 기다려라!(너무 어려워.. 예시 보며 이해하자😂)
async function 함수이름(){
await 비동기_처리_메소드이름();
async function logItems() {
var resultItems = await fetchItems();
console.log(resultItems); // [1,2,3]
}
-> await 사용 안했다면, 데이터 받아온 후 콘솔 출력할 수 있게 콜백함수나 .then() 사용해야했을 것!
async function logTodoTitle() {
try {
var user = await fetchUser();
if (user.id === 1) {
var todo = await fetchTodo();
console.log(todo.title); // delectus aut autem
}
} catch (error) {
console.log(error);
}
}
-> try, catch 사용도 확인해보기!