Callback / Promise

효딩딩·2022년 8월 24일
0

CallBack

  • 비동기 처리 방식 중 하나이다.
  • 문제점 : Callback hell 비동기 처리 로직을 위해 콜백 함수를 연속해서 사용할 때 발생하는 문제이다. 콜백안에 콜백을 계속 무는 형식으로 이러한 코드 구조는 가독성이 떨어지고 로직을 변경하기 어렵다.
  • 해결방법 : Promise나 Async를 사용하는 방법

Promise

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

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

1. Pending(대기) : 비동기 처리 로직이 아직 완료되지 않은 상태
2. Fulfilled(이행) : 비동기 처리가 완료되어 Promise가 결과 값을 반환해준 상태
3. Rejected(실패) : 비동기 처리가 실패하거나 오류가 발생한 상태

: reject() 메서드를 실행하면 실패 상태가 된다. 실패상태가 되면 실패한 이유(실패 처리의 결과 값)을 catch()로 받을 수 있다.

출처:
https://blog.naver.com/dlrmawnl/222908361002
https://blog.naver.com/wx776654/222868891875
https://velog.io/@miniyoung37/TIL-Callback-vs-Promise-vs-asyncawait


(영문 해석)

Callback function

  • A callback function is a function passed into another function as an argument, which is called (or executed) inside the otherFunction.

So the basic way to handle asynchronous operations is through callbacks. But when working with a lot of dependent asynchronous operations, you quickly end up in 'callback hell'.

Promise

  • The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
  • Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

Source:
https://linuxhint.com/callback-promise-javascript-examples/
https://www.loginradius.com/blog/engineering/callback-vs-promises-vs-async-await/
https://javascript.plainenglish.io/callback-vs-promise-and-async-await-1e46bc1780f4

profile
어제보다 나은 나의 코딩지식

0개의 댓글