반응형
  • 기본적으로 Promise는 함수에 콜백을 전달하는 대신에 콜백을 첨부하는 방식의 객체를 말한다.
  • Promise를 이용하면 콜백함수를 중첩으로 호출해야 할때 피라미드 생성을 피할 수 있다.

기본 Promise 생성

// 비동기 동작이 필요한 Promise 정의
var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 3000);
});

// Promise 함수 실행
promise1.then(function(value) {
  console.log(value);
  // expected output: "foo"
});

console.log(promise1);
// expected output: [object Promise]

 

일반적인 콜백 함수 호출

function successCallback(result) {
  console.log("Audio file ready at URL: " + result);
}

function failureCallback(error) {
  console.log("Error generating audio file: " + error);
}

createAudioFileAsync(audioSettings, successCallback, failureCallback);

콜백 중첩 호출

  • 피라미드 패턴으로 가독성 X
doSomething(function(result) {
  doSomethingElse(result, function(newResult) {
    doThirdThing(newResult, function(finalResult) {
      console.log('Got the final result: ' + finalResult);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

 

Promise 호출

function successCallback(result) {
  console.log("Audio file ready at URL: " + result);
}

function failureCallback(error) {
  console.log("Error generating audio file: " + error);
}

const promise = createAudioFileAsync(audioSettings); 
promise.then(successCallback, failureCallback);

 

Promise 중첩 호출

  • then 에 넘겨지는 인자는 선택적(optional)
  • catch(failureCallback)는 then(null, failureCallback) 의 축약
doSomething().then(function(result) {
  return doSomethingElse(result);
})
.then(function(newResult) {
  return doThirdThing(newResult);
})
.then(function(finalResult) {
  console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);


// 축약 표현식으로 변경시
doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => {
  console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);
반응형

+ Recent posts