🐨CoalaCoding
DocsExamplesTry itBoardB반B반
🐨CoalaCoding

개발자를 위한 한국어 웹 기술 문서

문서

  • JavaScript
  • Web Publishing
  • React
  • Python

커뮤니티

  • 게시판
  • 예제 모음
  • Try it 에디터

기타

  • GitHub
  • 관리자
© 2026 CoalaCoding. All rights reserved.
  • start
  • class
  • ai이미지-생성기-구현
  • 자료형
  • async--await
  • 변수와자료형
  • xmlhttprequest-부터axios-까지
  • 1-자바스크립트와-ecma
  • reduce
  • 캘린더-만들기
  • generator
  • destructuring
  • spread-operator
  • module-export-import
  • http-통신-이란
  • 시작
  • 2-자바스크립트-코드-실행-과정-및-용어정리
  • map
  • 동기와-비동기
  • 연산자
  • promise-thencatch
  • 3-실행컨텍스트와-스코프
  • 콜백-함수
  • 제어문
  • 4-클로저
  • windowlocation
  • 함수
  • 5-객체
  • 이벤트
  1. 홈
  2. 문서
  3. JavaScript
  4. JavaScript 기초
  5. async--await

async--await

코드 블록의 Try it Yourself 버튼으로 직접 실행할 수 있다.

구문

콜백지옥

Info: 비동기적 처리를 할땐 콜백을 활용하게 되는데 하다보면 콜백 함수가 중첩되면서 콜백 지옥에 빠지게 된다.

  • 1초후에 일을 하는 timer 함수가 있다
timer(1000, function () {
      console.log("작업");
    });
  • timer 함수에 1초후 콜백함수를 실행시키고 또 콜백을 실행시키게 될경우… 콜백지옥에 빠지게된다
timer(1000, function () {
	console.log("작업");
  timer(1000, function () {
    console.log("작업");
    timer(1000, function () {
      console.log("작업");
    });
  });
});

콜백지옥에서 탈출 → promise

Info: 콜백지옥에서 탈출하기 위해서는 promise 객체의 then 을 사용한다.

  • .then (함수)
timer(1000)
	.then(function () {
		console.log("작업");
		return timer(1000);
	})
	.then(function () {
		console.log("작업");
		return timer(1000);
	})
	.then(function () {
		console.log("작업");
	});
  • async & await 로 좀더 간단히 작성
async function run(){
	await timer(1000)	
			console.log("작업");
	await timer(1000);
			console.log("작업");
	await timer(1000)
			console.log("작업");
}
run();

async & await

Info: then 을 이용하여 콜백을 작성후 async로 변경해본다

  • .then (함수)
    • timer 함수는 promise 값을 반환하도록 작성되어있다.
    • then 함수를 사용하여 1초후 실행을 비동기적으로 여러번 시키는 코드를 작성해보자
function timer(time) {
  return new Promise(function (resolve) {
    setTimeout(() => {
      resolve(time);
    }, time);
  });
}
console.log('start')
timer(1000)
  .then((time) => {
    console.log("time:" + time);
    return timer(time + 1000);
  })
  .then((time) => {
    console.log("time:" + time);
    return timer(time + 1000);
  })
  .then((time) => {
    console.log("time:" + time);
		console.log('end')
  });

  • async & await 로 좀더 간단히 작성
const run = async () => {
  console.log("start");
  let time = await timer(1000);
  console.log("time:" + time);
  time = await timer(time + 1000);
  console.log("time:" + time);
  time = await timer(time + 1000);
  console.log("end");
};

run();

목차

  • 구문