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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.