javascript Promise

최종윤·2024년 1월 14일
0

JAVASCRIPT

목록 보기
1/6

ajax api는 비동기 방식으로 수행됩니다.
이를 위해 콜백함수에 같이 수행되야 하는 기능을 넣어 요청으로 받은 데이터를 가지고
온 다음 출력할 수 있도록 했습니다.
promise를 이용하면 콜백함수에 순서대로 수행돼야하는 출력 기능을 포함시키지 않고
비동기 방식일 때 발생할 수 있는 문제를 해결할 수 있습니다.

Promise

Promise는 javascript 비동기 처리를 돕는 객체입니다.
비동기 처리란 ‘특정 코드의 실행이 완료될 때까지 기다리지 않고 다음 코드를 먼저 수행하는 자바스크립트의 특성입니다.
Promise는 서버에서 받아온 데이터를 표시할 때 사용합니다.

$.get('url 주소/products/1', function(response) {
  // ...
});

위 API가 실행되면 서버에다가 ‘데이터 하나 보내주세요’ 라는 요청을 보내죠. 그런데 여기서 데이터를 받아오기도 전에 마치 데이터를 다 받아온 것 마냥 화면에 데이터를 표시하려고 하면 오류가 발생하거나 빈 화면이 뜹니다. 이와 같은 문제점을 해결하기 위한 방법 중 하나가 프로미스입니다.

function getData(callback) {
  // new Promise() 추가
  return new Promise(function(resolve, reject) {
    $.get('url 주소/products/1', function(response) {
      // 데이터를 받으면 resolve() 호출
      resolve(response);
    });
  });
}

// getData()의 실행이 끝나면 호출되는 then()
getData().then(function(tableData) {
  // resolve()의 결과 값이 여기로 전달됨
  console.log(tableData); // $.get()의 reponse 값이 tableData에 전달됨
});

ajax의 콜백에 포함시키지 않고 then에 출력기능을 넣었습니다.
Promise의 실행이 끝나면 then()이 호출됩니다.
data를 받아온 다음 출력할 수 있습니다.

promise 3가지 상태(states)

Promise는 pending, fulfilled, rejected 의 3가지 상태를 갖습니다.
pending은 new Promise() 가 호출되고 아직 resolve, reject가 호출되지 않은
비동기 처리 실행 중인 상태
fulfilled는 비동기 처리 실행 완료한 상태
rejected 비동기 처리 실패한 상태를 말합니다.

Promise를 생성자 안에서 resolve(data) 를 호출 하면 data를 promise 결과값으로
사용하고 fulfilled 상태가 돼서 promise 에서 then()을 호출하여 처리하고
then(callbackFunc(data)) 이렇게 callbackFunc에 넣어 data 사용 가능합니다.

Promise 생성자 안에서 reject(new Error("Request is failed"));
이렇게 에러 정보를 넣어 호출하면 Promise에서 catch()를 호출하여 처리하고 catch(callbackFunc(err)) 파라미터로 에러 정보 받아 사용 가능합니다.

Promise의 then(), catch()에서 앞에서 같이 data또는 err처럼 1개의 parameter만 받아 호출하는 경우 then((data)=>func1(data)) 또는
catch((err)=>console.log(err)) 는 생략하여 다음과 같이 표현가능합니다.
new Promise(function(resolve, reject){
setTimeout(function() {
resolve(1);
}, 2000);
})
.then(func1)
.catch(console.log);

Promise Chaining

Promise에서 then(callbackFunc(data))는 callbackFunc의 return 값을 갖는
Promise를 반환하므로 then을 연달아 사용 가능합니다.

Promise Chaining 사례

getData(userInfo) .then(parseValue) .then(auth) .then(diaplay);
유저 정보를 가져온 다음 파싱을 해야하고 그 한 다음 인증해야하고 이렇게 순서를 지켜서 처리해야 합니다.
유저 정보 가져오는 것도 서버에서 가져오니 ajax 이용하고 인증하면서 ajax통신을 이용해 비동기 방식이 될 수도 있고 promise를 연달아 사용해야할 것입니다.

promise에서 콜백함수 사용할 때 인자 1개 받아 함수에 전달해 사용하는 경우
함수 이름만 전달하면 동일하게 동작합니다.

Promise error handling

then(handleSuccess, handleError) 처럼 then의 2번째 인자 또는
catch() 를 통해 error handling을 할 수 있습니다.
가급적 catch()를 사용하는데 then의 2번쨰 인자를 사용하면
다음과 같은 문제가 발생합니다.

// then()의 두 번째 인자로는 감지하지 못하는 오류
function getData() {
  return new Promise(function(resolve, reject) {
    resolve('hi');
  });
}

getData().then(function(result) {
  console.log(result);
  throw new Error("Error in then()"); // Uncaught (in promise) Error: Error in then()
}, function(err) {
  console.log('then error : ', err);
});

then 첫 번째 함수에서 발생한 에러를 2번 째 함수에서 처리하지 못합니다.

// catch()로 오류를 감지하는 코드
function getData() {
  return new Promise(function(resolve, reject) {
    resolve('hi');
  });
}

getData().then(function(result) {
  console.log(result); // hi
  throw new Error("Error in then()");
}).catch(function(err) {
  console.log('then error : ', err); // then error :  Error: Error in then()
});

catch로 에러처리를 한 경우 then에서 발생한 에러를 받아서 처리할 수 있습니다.

profile
https://github.com/jyzayu

0개의 댓글