Simplifying Code Flows with Promises

In this section, you’ll add another API to your lib/search.js file. Like the /search/books API from last section, this /suggest API will hit your Elasticsearch cluster for information, but this time we’ll use Promises rather than callbacks to manage asynchronous control flow.

Fulfilling Promises

To understand Promises, it helps to start with a brief review of JavaScript code flow and the mechanisms for structuring it. Whenever a regular JavaScript function starts executing, it will finish in one of two ways: either it will run to completion (success) or it will throw an exception (failure).

For synchronous code this is good enough, but for asynchronous code we need a bit more. The Node.js core module callbacks ...

Get Node.js 8 the Right Way now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.