promise vs callback

김선우·2022년 6월 27일
0

callback

전에도 포스팅 한적이 있듯이 비동기 처리 방식 중 하나이다.

콜백지옥이라는 문제의 소지를 갖고있는 녀석이기도 하다. 또한 그 해결방법으로 async await를 사용하기도 했었다.

ex)

const printString = (string) => {
    setTimeout(() => {
        console.log(string)
    },
    Math.floor(Math.random() * 100) + 1
  )
}

const printAll = () => {
    printString("A")
    printString("B")
    printString("C")
}
printAll()
// 무작위로 출력

..............................................................................

// callback을 이용한 출력
const printString = (string, callback) => {
    setTimeout(() => {
        console.log(string)
        callback()
    },
    Math.floor(Math.random() * 100) + 1
  )
}

const printAll = () => {
    printString("A", () => {
           printString("B", () => {
                  printString("C", () => {})
           })
    })
}
printAll()
// A, B, C 순서로 출력

promise

프로미스는 자바스크립트 비동기 처리에 사용되는 객체이다.
자바스크립트에서 비동기 처리란 ? '특정 코드의 실행이 완료될 때까지 기다리지 않고 다음 코드를 먼저 수행하는 자바스크립트의 특성'

Promise의 3가지 상태
: Promise를 사용할 때 알아야 하는 가장 기본적인 개념이 바로 Promise의 상태이다. 이는 Promise의 처리 과정을 의미한다. new Promise()로 Promise를 생성하고 종료될 때까지 3가지 상태를 가진다.

Pending(대기) : 비동기 처리 로직이 아직 완료되지 않은 상태

new Promise(function (resolve, reject) {
  // ...
});
: 메서드를 호출하면 대기 상태가 되고, 호출할 때 콜백 함수의 인자로 resolve, reject에 접근할 수 있다.

Fulfilled(이행) : 비동기 처리가 완료되어 Promise가 결과 값을 반환해준 상태

function getData() {
  return new Promise(function (resolve, reject) {
    var data = 100;
    resolve(data);
  });
}

// resolve()의 결과 값 data를 resolvedData로 받음
getData().then(function (resolvedData) {
  console.log(resolvedData); // 100
});
: resolve를 실행하면 이행 상태가 된다. 이후 then()을 이용하여 처리 결과 값을 받을 수 있다.

Rejected(실패) : 비동기 처리가 실패하거나 오류가 발생한 상태

function getData() {
  return new Promise(function (resolve, reject) {
    reject(new Error("Request is failed"));
  });
}

// reject()의 결과 값 Error를 err에 받음
getData().then().catch(function (err) {
  console.log(err); // Error: Request is failed
});
: reject() 메서드를 실행하면 실패 상태가 된다. 실패상태가 되면 실패한 이유(실패 처리의 결과 값)catch()로 받을 수 있다.

// example

function getData() {
  return new Promise(function (resolve, reject) {
    $.get('url 주소/products/1', function (response) {
      if (response) {
        resolve(response);
      }
      reject(new Error("Request is failed"));
    });
  });
}

// Fulfilled 또는 Rejected의 결과 값 출력
getData().then(function (data) {
  console.log(data); // response 값 출력
}).catch(function (err) {
  console.error(err); // Error 출력
});
Promise 형태
// promise 이용
const printString = (string) => { 
    // callback을 인자로 받지 않는다
    // new Promise() 추가
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log(string)
   		resolve()
    	},
   		 Math.floor(Math.random() * 100) + 1
  		)
    })
}

const printAll = () => {
    printString("A")
    .then(() => {
        printString("B")
    })
    .then(() => {
        printString("C")
    })
    // 만약 reject가 사용되면, 이곳에 catch를 이용하여 error 표시
}
printAll()
Promise Chaning
function sitAndCode(){
    return new Promise((resolve, reject) => {
        setTimeout(() => { resolve('sit and code') }, 100) 
    })
}
function eatLunch(){
    return new Promise((resolve, reject) => {
        setTimeout(() => { resolve('eat Lunch') }, 100) 
    })
}
function goToBed(){
    return new Promise((resolve, reject) => {
        setTimeout(() => { resolve('go To Bed') }, 100) 
    })
}

sitAndCode()
.then(() => {
    return eatLunch
})
.then(() => {
    return goToBed
})

Async / Await

기존 비동기 처리 방식인 Callback & Promise의 단점을 보완하고 개발자가 읽기 좋은 코드로 작성 가능

// 기본 문법
async function 함수명() {
await 비동기처리메서드_명();
}
: 함수 앞에 async 라는 예약어를 붙인다. 그리고 함수 내부 로직 중 HTTP 통신을 하는 비동기 처리 코드 앞에 await를 붙인다.

여기서 중요한 것은 비동기 처리 메서드가 꼭 Promise 객체를 반환해야 await가 의도한 대로 동작한다는 사실
일반적으로 await의 대상이 되는 비동기 처리 코드는 Axios 등 Promise를 반환하는 API 호출 함수

function sitAndCode(){
    return new Promise((resolve, reject) => {
        setTimeout(() => { resolve('sit and code') }, 100) 
    })
}
function eatLunch(){
    return new Promise((resolve, reject) => {
        setTimeout(() => { resolve('eat Lunch') }, 100) 
    })
}
function goToBed(){
    return new Promise((resolve, reject) => {
        setTimeout(() => { resolve('go To Bed') }, 100) 
    })
}

var result = async () => {
    const one = await sitAndCode();
    console.log(one);
    const two = await eatLunch();
    console.log(two);
    const three = await goToBed();
    console.log(three);
}
result();
profile
생각은 나중에..

0개의 댓글