비동기 처리 - 1. 비동기와 콜백 글 보러 가기 

비동기 처리 - 2.  Promise 글 보러 가기 

 


 

개요

 


 

1. Promise Chaining (프로미스 체이닝)

의미

순차적으로 처리해야 하는 비동기 작업이 여러 개 있는 경우 사용하는 기법

 

방법 1 : 프로미스를 리턴
  • resolve (result) 하는 것
  • 예시 코드 
return new Promise((resolve, reject) => {   
  this._detector.estimateHands(imageData).then(result => {
      this._result = result;
      console.log(`this._result: `, this._result);

      this._result.forEach((res) => {
          console.log(`${res.handedness} hand keypoints:`);
          res.keypoints.forEach((keypoint, i) => {
              let x = keypoint.x - 320;
              let y = keypoint.y - 240;
              console.log(`Keypoint ${i}: [${x}, ${y}]`);
          })
      })
      resolve(this._result);
  }).catch(e => {
      reject(e);
  });
})

 

방법 2: .then을 여러 번 사용
new Promise(function(resolve, reject) {
  setTimeout(() => resolve(1), 1000); // (*)
}).then(function(result) { // (**)
  alert(result); // 1
  return result * 2;
}).then(function(result) { // (***)
  alert(result); // 2
  return result * 2;
}).then(function(result) {
  alert(result); // 4
  return result * 2;
});

 

fetch와 프로미스 체이닝 함께 이용 가능
  • fetch
    • JS에서 제공하는 네트워크 요청의 생성, 응답을 다루기 위한 API
    • HTTP 요청을 보내거나 서버에서 데이터를 가져올 때 사용됨
    • Promise 기반의 비동기 방식으로 동작
    • 브라우저 환경 or Node.js 에서 사용 가능
  • 예시 코드 : Promise.race 를 사용하여 fetch 요청에 타임아웃을 설정
return Promise.race([
  fetch(resource, Object.assign({signal}, init)).then(response => {  //fetch 함수를 이용하여 네트워크 리소스에 대한 요청 수행 
      clearTimeout(timeoutID);  //fetch 요청이 완료되면 타임아웃을 취소하기 위해 사용됨
      return response;
  }),
  new Promise((resolve, reject) => {
      timeoutID = setTimeout(() => {
          if (controller) controller.abort();
          reject(new Error(`Fetch timed out after ${timeout} ms`));
      }, timeout);
  })
]);

 


 

2. Error Handling (에러 핸들링)

// 실행 순서: catch -> then
new Promise((resolve, reject) => {
  throw new Error("에러 발생!");
}).catch(function(error) {
  alert("에러가 잘 처리되었습니다. 정상적으로 실행이 이어집니다.");
}).then(() => alert("다음 핸들러가 실행됩니다."));
  • .then 구문 안에서 throw new Error 하고, .catch 구문으로 에러 다시 던져서 처리하면 보다 효과적으로 에러 처리 됨
  • 만약 위처럼 에러 핸들링하지 않는다면, 서버에 에러를 알리지 않은 채 스크립트가 죽고 콘솔창에 메시지가 출력 됨.
    : 이 경우 JS 는 전역 에러를 생성하는데, 다시 복구가 어려움

+ Recent posts