Callbacks and Promises

There are two mechanisms that can be used to make asynchronous function calls: Callbacks and Promises.

Callbacks

Callbacks or callback functions are functions passed to another function (referred to as the higher-order function) as a parameter. The higher-order function can call the callback function to execute the functionality defined in the callback function.

Functions that need to make an asynchronous request to a microservice using an API need to be passed one or more callback functions. A function sends the API request and processes it by executing the next instruction. When the microservice returns a response, the callback function is executed that handles the data received from the microservice. When multiple callback functions are passed, they can be executed conditionally, depending on what the response is from the microservice.

Promises

A Promise is a placeholder for a value that is pending to be determined based on the execution of an asynchronous function.

It lets asynchronous methods return values like synchronous methods instead of returning the actual value. The asynchronous method returns a promise, as it also means in the English language is a promise to return the value in the future at some point.

A promise has one of these states at any time:

  • Pending: initial state, neither resolved nor rejected.
  • Resolved: meaning that the operation is completed successfully.
  • Rejected: meaning that the operation failed.

A pending promise can either be resolved with a value or rejected with a reason (usually an error). When either of these options happens, the associated handlers are called.

Both callbacks and promises are broadly similar, and both can be used, depending on the programmer's preference.

This is a relatively complex concept to grasp and implement, so we will not be going into depth into this. But it is good to be familiar with the concept in case you need to access microservices that use this approach.