HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🐣
프론트엔드 데브코스 3기 교육생
/
😃
나영팀
/
비동기 ⇒ Promise, Async, await

비동기 ⇒ Promise, Async, await

발표일
Oct 31, 2022
작성자
박민형
비동기 ⇒ Promise, async, await
동기 vs 비동기
  • 동기 ⇒ 동시에 여러 작업을 수행할 수 없음, 흐름을 예측하기 쉽다. 먼저 수행되고 나중에 수행되는 것들이 명확하다.
  • 비동기 ⇒ 동시에 여러 작업을 수행할 수 있음, 흐름을 예측하기 어려움
Promise
  • 비동기 작업의 단위
  • resolve와 reject는 또다른 함수로서 resolve는 비동기 작업이 성공 했을 경우, reject는 비동기 작업이 실패 했을 경우
  • then 메소드는 해당 Promise 가 성공했을 때의 동작(인자로 함수)
  • catch 메소드는 실패했을 경우(인자로 함수)
async
  • Promise 와 밀접한 연관을 가지고 있음
  • async 의 return 값은 Promise
  • await ⇒ async 함수 안에서만 사용 가능, Promise가 완료될 때 까지 기다림
  • await [[Promist 객체]]
비동기의 특징
  • 실제 작업과 그 작업의 후속조치를 따로 분리(then, catch)
  • async, await를 통해 하나의 흐름속에서 코딩 가능
  • 실제 작업이 끝난 다음 후속 조치를 하는 것이 아니라 실제 작업이 끝나길 기다린 다음 다음 코드를 수행 ⇒ 동기 코드 처럼 사용할 수 있게 함
const promise1 = new Promise((resolve, reject) => { resolve(); }); promise1 .then(() => { console.log("then!"); }) .catch(() => { console.log("catch!"); });
function startAsync(age) { return new Promise((resolve, reject) => { if (age > 20) resolve(`${age} success`); else reject(new Error(`${age} is not over 20`)); }); } setTimeout(() => { const promise1 = startAsync(25); promise1 .then((value) => { console.log(value); }) .catch((error) => { console.error(error); }); const promise2 = startAsync(15); promise2 .then((value) => { console.log(value); }) .catch((error) => { console.error(error); }); }, 1000); 25 success Error: 15 is not over 20 at /home/taehoon/Desktop/playground-nodejs/index.js:4:17 at new Promise (<anonymous>) at startAsync (/home/taehoon/Desktop/playground-nodejs/index.js:2:10) at Timeout._onTimeout (/home/taehoon/Desktop/playground-nodejs/index.js:17:20) at listOnTimeout (internal/timers.js:554:17) at processTimers (internal/timers.js:497:7)
// 기존 // function startAsync(age) { // return new Promise((resolve, reject) => { // if (age > 20) resolve(`${age} success`); // else reject(new Error("Something went wrong")); // }); // } async function startAsync(age) { if (age > 20) return `${age} success`; else throw new Error(`${age} is not over 20`); } setTimeout(() => { const promise1 = startAsync(25); promise1 .then((value) => { console.log(value); }) .catch((error) => { console.error(error); }); const promise2 = startAsync(15); promise2 .then((value) => { console.log(value); }) .catch((error) => { console.error(error); }); }, 1000);
function setTimeoutPromise(ms) { return new Promise((resolve, reject) => { setTimeout(() => resolve(), ms); }); } async function startAsync(age) { if (age > 20) return `${age} success`; else throw new Error(`${age} is not over 20`); } async function startAsyncJobs() { await setTimeoutPromise(1000); const promise1 = startAsync(25); try { const value = await promise1; console.log(value); } catch (e) { console.error(e); } const promise2 = startAsync(15); try { const value = await promise2; console.log(value); } catch (e) { console.error(e); } } startAsyncJobs();