home강의 홈으로
Section 14. 비동기 프로그래밍
Lesson 4. async & await

async 함수

  • 프로미스를 기반으로 동작
  • 마치 동기 코드처럼 직관적으로 코딩을 할 수 있음
  • 👉 MDN 문서 보기
function getMult10Promise (number) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(number * 10); }, 1000); }); } async function doAsyncWorks () { const result1 = await getMult10Promise(1); console.log(result1); const result2 = await getMult10Promise(2); console.log(result2); const result3 = await getMult10Promise(3); console.log(result3); } doAsyncWorks(); console.log('💡 이 문구가 먼저 출력됨');
  • await - 코드의 진행을 멈추고 프로미스로부터 답을 받아냄
  • 💡 awaitasync 함수 또는 모듈 내에서만 사용 가능
  • 👉 MDN 문서 보기


💰 10% 이자, 채무자 파산가능성 10%, 5번 빌려주기

// 빌린 금액으로 약속을 하는 함수 function moneyLend (borrow) { return new Promise((resolve, reject) => { console.log(`채무 ${borrow}만원`); setTimeout(() => { if (Math.random() < 0.1) { reject('채무자 파산'); } resolve(borrow * 1.1); }, 1000); }); } async function lend5times () { try { const lend1 = await moneyLend(20); const lend2 = await moneyLend(lend1); const lend3 = await moneyLend(lend2); const lend4 = await moneyLend(lend3); const lend5 = await moneyLend(lend4); console.log(`💰 반납 ${lend5}만원`); } catch (msg) { console.error(msg); } finally{ console.log('- - 대금업 종료 - -'); } } lend5times();
  • 💡 reject 가능성이 있는 경우 try...catch...finally 문으로
  • 일반 Promise문보다 가독성 좋음


🏃🏃🏃 릴레이

const DEADLINE = 1400; function getRelayPromise (name, start, failMsg) { console.log(`👟 ${name} 출발`); // 💡 랜덤 시간만큼 달리고 결과를 반환하겠다는 약속을 만들어 반환 return new Promise((resolve, reject) => { const time = 1000 + Math.random() * 500; setTimeout(() => { if (time < DEADLINE) { console.log(`🚩 ${name} 도착 - ${(start + time)/1000}초`); resolve(start + time); } else { console.log(failMsg); reject((start + time) / 1000); } }, time); }) } async function relay5 () { try { const time1 = await getRelayPromise('철수', 0, '철수부터 광탈입니다. ㅠㅠ'); const time2 = await getRelayPromise('영희', time1, '영희가 완주하지 못했네요.'); const time3 = await getRelayPromise('돌준', time2, '돌준이 분발해라.'); const time4 = await getRelayPromise('정아', time3, '정아에게 무리였나보네요.'); const time5 = await getRelayPromise('길돈', time4, '아아, 아깝습니다...'); } catch (msg) { console.log(`😢 완주 실패 - ${msg}초`); } finally { console.log('- - 경기 종료 - -'); } } relay5();

🤔얄코에게 질문하기질문은 반.드.시 이리로 보내주세요! ( 강의사이트 질문기능 ✖ )

강의에서 이해가 안 되거나 실습상 문제가 있는 부분,
설명이 잘못되었거나 미흡한 부분을 메일로 알려주세요!

답변드린 뒤 필요할 경우 본 페이지에
관련 내용을 추가/수정하도록 하겠습니다.

이메일 주소
yalco@yalco.kr
메일 제목 (반드시 아래 제목을 붙여넣어주세요!)
[질문] 제대로 파는 자바스크립트 (유료 파트) 14-4

🛑질문 전 필독!!

  • 구글링을 먼저 해 주세요. 들어오는 질문의 절반 이상은 구글에 검색해 보면 1분 이내로 답을 찾을 수 있는 내용들입니다.
  • 오류 메시지가 있을 경우 이를 구글에 복붙해서 검색해보면 대부분 짧은 시간 내 해결방법을 찾을 수 있습니다.
  • 강의 페이지에 추가사항 등 놓친 부분이 없는지 확인해주세요. 자주 들어오는 질문은 페이지에 추가사항으로 업데이트됩니다.
  • "유료파트의 강의페이지는 어디 있나요?" - 각 영상의 시작부분 검은 화면마다 해당 챕터의 강의페이지 링크가 있습니다.
  • 질문을 보내주실 때는 문제가 어떻게 발생했고 어떤 상황인지 등을 구체적으로 적어주세요. 스크린샷을 첨부해주시면 더욱 좋습니다.
🌏 Why not change the world?