Amanda Merla Amanda Merla - 2 years ago 132
Node.js Question

Node.js promises, async, or just callbacks

Can you explain to a beginner the differences between "promises", "async", and "callbacks". How do these terms relate to one another? Are these the same thing? Different things? When do I use which?

Answer Source

Async is the general design pattern of starting a computation and providing a function or registering a handler that will eventually get called with the result of the computation when it has completed (as opposed to blocking and waiting for the computation to complete before starting additional work). Without async, starting multiple computations simultaneously requires the use of threads.

A "callback" refers to the function that you provide to an async computation that will get invoked when that computation completes. It is called a "callback" because it gets called by the async function, and in getting called, it returns the flow of control back into code that you have control over.

A "Promise" is a specific JavaScript prototype and associated framework that brings consistency to code that is written in an asynchronous style. A Promise represents an async computation that may or may not have completed (successfully or unsuccessfully) and provides a means of operating on the result or handling errors regardless of the state of completion of the asynchronous computation. The Promise API also provides utilities for combining the outputs of multiple asynchronous computations (such as waiting for one of or all of a set of asynchronous computations to complete before the next calculation).

To give a simple example without Promises:

var addThen = function(a, b, handler) {
  var result = a + b;

// ...
addThen(2, 3, console.log);  // prints 5
// ...

And the equivalent with Promise:

var add = function(a, b) {
  return Promise.resolve(a + b);

// ...
add(2, 3).then(console.log); // prints 5
// ...

Async code can be written both with and without Promises, but the primary advantage of using Promise is consistency (e.g. where in the argument list the success callback and failure callbacks go, whether a failure callback is supported or not, etc.) and support libraries that can combine them together.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download