javascript


Promise

  • 비동기 작업을 동기처럼 처리하기 위한 방법이다.
  • 콜백을 인자로 넘겨주는 방식이 아닌, 콜백을 붙이는 방식이기 때문에 콜백지옥현상을 해결할 수 있다.
  • 비동기 작업이 성공하거나 실패한 뒤에 콜백 함수를 실행한다.

chaining

  • then() 함수는 Promise 객체를 리턴하기 때문에 then() 함수를 여러번 사용해 여러개의 콜백을 호출할 수 있다.
  • 에러 catch 후 함수를 호출할 수 있다.
new Promise((resolve, reject) => {
    console.log('Initial');
    resolve();
})
    .then(() => {
        throw new Error('Something failed');
        console.log('Do this');
    })
    .catch(() => {
        console.log('Do that');
    })
    .then(() => {
        console.log('Do this, whatever happened before');
    });

/*
 * Initial
 * Do that
 * Do this, watever happend before
 */

composition

  • resolve(value)
    • Pending(대기) : 비동기 처리 로직이 아직 완료되지 않은 상태
    • Fulfilled(이행) : 비동기 처리가 완료되어 프로미스가 결과 값을 반환해준 상태 pending 상태에서 fulfilled 상태로 넘어가며 value(결과값)을 반환한다.
  • reject(reason)
    • 실패한 promise 반환
  • all(arr[func1, func2, …])
    • 비동기 작업을 병렬로 처리

binding Method

  • call(thisArg, arg1, arg2, …)
  • apply(thisArg, [arg1, arg2, …])
  • bind
    • call, apply method와 달리 함수가 호출되지 않고 새로운 함수를 반환한다.
    • useState의 dispatch가 bind 부분적용 함수로, action을 보내 state를 업데이트 할 수 있는 것을 확인했다.

async/await과 promise의 차이

  • 에러 핸들링 함수가 없어 try-catch() 문으로 에러 처리 ⇒ 에러처리가 쉽다
  • promise는 Promise 객체를 반환하고, async/await은 결과값을 받환한다.