Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

사고쳤어요

[Node.js] Promise와 비동기 처리 본문

웹 풀스택

[Node.js] Promise와 비동기 처리

kevinmj12 2025. 3. 19. 23:39

Promise는 비동기로 처리되는 Javascript에서 작업을 효율적으로 관리하기 위해 사용되는 객체이다.

function step1(callback) {
    setTimeout(() => {
        console.log("Step 1 완료");
        callback();
    }, 1000);
}

function step2(callback) {
    setTimeout(() => {
        console.log("Step 2 완료");
        callback();
    }, 1000);
}

function step3(callback) {
    setTimeout(() => {
        console.log("Step 3 완료");
        callback();
    }, 1000);
}

step1(() => {
    step2(() => {
        step3(() => {
            console.log("끝");
        });
    });
});

예를 들어 다음과 같이 콜백함수를 여러 번 사용한다 생각해보자.

함수를 3번만 사용하였음에도 불구하고 깊이가 매우 깊어지고 알아보기 힘들어진다.

그리고 깔끔하게 콜백을 여러 번 사용할 수 있도록 Promise가 등장하였다.

 

const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("완료");
    }, 1000);
});

myPromise.then((message) => {
    console.log(message);
});

// output: 
// 완료

Promise의 기본적인 사용 방법은 위와 같다.

Promise를 선언한 뒤 resolve()에 완료되었을 때 리턴될 값을 넣으면 해당 값이 리턴된다.

 

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("완료");
  }, 1000);
});

myPromise
  .then((message) => {
    console.log(message);
    return message + "!!";
  })
  .then((message) => {
    console.log(message);
    return message + "!!";
  })
  .then((message) => {
    console.log(message);
  });

//   output:
//   완료
//   완료!!
//   완료!!!!

Promise는 위와 같이 .then()을 여러 번 사용하여 체이닝(Chaining)을 진행할 수도 있다.

맨 처음 "완료"를 출력한 뒤 "!!"가 추가된 "완료!!"를 리턴하고,

"완료!!"를 출력한 뒤 "!!"가 추가된 "완료!!!!"를 리턴한다.

위와 같은 과정을 통해 비동기 함수들의 실행 순서를 설정해줄 수 있다.

 

function step1() {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log("Step 1 완료");
            resolve();
        }, 1000);
    });
}

function step2() {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log("Step 2 완료");
            resolve();
        }, 1000);
    });
}

function step3() {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log("Step 3 완료");
            resolve();
        }, 1000);
    });
}

step1()
    .then(() => step2())
    .then(() => step3())
    .then(() => console.log("끝!"));

이를 활용하면 맨 처음에 콜백을 여러 번 했을 때 지저분했던 코드와는 달리, 깔끔하게 코드를 작성할 수 있다.

 

function step1() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Step 1 완료");
      resolve();
    }, 1000);
  });
}

function step2() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Step 2 완료");
      resolve();
    }, 1000);
  });
}

function step3() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Step 3 완료");
      resolve();
    }, 1000);
  });
}

async function runSteps() {
  await step1();
  await step2();
  await step3();

  console.log("끝");
}

runSteps();

추가적으로 async/await을 함께 사용할 수도 있다.

새로운 runSteps()라는 비동기 함수를 만들어준 뒤

해당 함수에서 await step1(), await step2(), await step3()를 순서대로 작성하여 실행 순서를 보장해주었다.