관리 메뉴

Silver Library (Archived)

[JS] callback 과 promises, 그리고 API? 본문

Face the fear, build the future/Revision Sector

[JS] callback 과 promises, 그리고 API?

Chesed Kim 2022. 10. 20. 15:10
반응형

callback 과 promises 에 대해 간략히 알아보자면.

 

promises (object)는 asynchronous, 그러니까 비동기적인 작업을 의도할 경우.

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

쓰임세: (의도한 결과가) 성공 또는 실패, 즉 이분법 설계.

 

callback (function)은 argument 로서 다른 function 에 passing 되도록 하는 것.

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

쓰임세: (예시의 시점에서 설명하자면) 콜백 argument 로 적어둔 대상 A function 가 끝난 이후, 해당 A 함수명에서 argument 로서 (추가) 작동되게 하는 것

예) synchronous callback 의 경우.

function greeting(name) {
  alert(`Hello, ${name}`);
}

function processUserInput(callback) {
  const name = prompt("Please enter your name.");
  callback(name);
}

processUserInput(greeting);

Note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. A good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. This structure is used in many modern web APIs, such as fetch().

참고: .then(), .fetch()