Node.js promises, asynchronous or just callback

Can you explain to newbies the differences between "promises", "async" and "callbacks". How are these terms related to each other? It is the same? Different things? When will I use which?

+3


source to share


1 answer


Async is a common design pattern for starting a computation and providing a function or registering a handler that will ultimately be called with the result of the computation when it completes (as opposed to blocking and waiting for the computation to complete before starting Extra Work). Without async, performing multiple computations at the same time requires the use of threads.

A "callback" refers to a function that you provide for an async computation that will be called when that computation completes. It is called a "callback" because it is called by the async function, and when called, it returns the flow of control back to the code you are controlling.

"Promise" is a specific JavaScript prototype and associated framework that provides consistency in asynchronous-style code. A Promise is an asynchronous computation that can complete or fail (succeed or fail) and provides a means to deal with result or processing errors regardless of the completion status of the asynchronous computation. The Promise API also provides utilities for combining the outputs of multiple asynchronous computations (such as waiting for one or an entire set of asynchronous computations to complete before the next computation).

To give a simple example without Promises:



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

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

      

And the equivalent with a promise:

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

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

      

Asynchronous code can be written with or without Promises, but the main advantage of using a Promise is consistency (for example, where callbacks and error callbacks go in the argument list, whether a failure callback is supported or not, etc.) .) and support libraries that can combine them.

+7


source







All Articles