Promises Tutorial by Irakli Nadareishvili
  • Introduction
  • Turning Callbacks Into Promises
  • Chain Parallel with Sequential
  • Conditions and Promises
  • Keeping Promise Chains Flat
  • Async and Await
  • Async/Await & Express, Mocha etc.
  • One More Thing (Go)...
  • One More Thing (Python)...
  • One More Thin (Nim)…
Powered by GitBook
On this page

Was this helpful?

Chain Parallel with Sequential

Let's dive into some examples to see how working with Promises in JavaScript looks and feels. We are not going to bore you with "this is how bad things were without Promises" examples. Since this guide primarily targets experienced JavaScript developers, we happily assume that you've written the kind of code we feature, without promises, and are well-familiar how that looked. If you are coming from another language - you probably don't care about the sad past, anyway. Either way - less is more, right?

A Summary Step After Parallel Steps

Let's demonstrate an example of running multiple async tasks in parallel and completing a summary step once all of them are finished.

Scenario: 1. Grab list of authors of a book from Google Books API 2. For each author, look up other books they have written. Make these calls in parallel, to save time 3. Once all parallel lookups are completed, output the final result.

Let's see how this looks:

const request = require('request');

function http_get(url) {
  return new Promise((resolve, reject) => {
    request(url, (error, response, body) => {
      if (!error && response.statusCode == 200) {
        resolve(body);
      } else {
        reject(error);
      }
    });
  });
}

// Google Books API Reference: https://developers.google.com/books/docs/v1/using
const base_url = "https://www.googleapis.com/books/v1/volumes?q=";

let book_url = `${base_url}isbn:1491956224`; // "Microservice Architecture"
http_get(book_url)
  .then(response_body => {
    const json_response = JSON.parse(response_body);
    const authors = json_response.items[0].volumeInfo.authors;
    let author_promises = [];
    authors.map(author => {
      let author_url = `${base_url}"inauthor:${author}"`;
      author_promises.push(namedRP(author, author_url));
    });

    return Promise.all(author_promises);
  })
  .then(author_responses => {
    console.log("Final results:");
    console.log(author_responses);
  })
  .catch(err => {
    // http request or parsing or something else failed...
    console.log(err);
  });

var namedRP = function (name, url) {
  return new Promise((resolve, reject) => {
    http_get(url)
      .then(body => {
        let response = {};
        json_body = JSON.parse(body);
        response.count = json_body.totalItems;
        response.name = name;
        resolve(response);
      }).catch(err => {
        reject(err);
      });
  });
};

// Expected output:
//
// [ { count: 3, name: 'Irakli Nadareishvili' },
//   { count: 3, name: 'Ronnie Mitra' },
//   { count: 3, name: 'Matt McLarty' },
//   { count: 6, name: 'Mike Amundsen' } ]
PreviousTurning Callbacks Into PromisesNextConditions and Promises

Last updated 5 years ago

Was this helpful?

Side note: source files of all examples and instructions for how to execute, are located at:

https://github.com/inadarei/promises123-code