Git Product home page Git Product logo

chained-promise's Introduction

Chained Promise: functional programming tools for recurring promises

Build Status Coverage Status Join the chat at https://gitter.im/google/chained-promise

We often find recurring patterns when handling asynchronous logic with promises, such as an HTTP endpoint that paginates and gives you a URL pointer to the next available dataset.

Chained Promise provides an extended Promise class that you can use to easily abstract out recurring patterns. See jsdocs for more detailed explanations.

Example

Suppose we are querying Wikipedia API to get the list of all linked pages from "Plato" page:

const apiPoint = "https://en.wikipedia.org/w/api.php?" +
  "action=query&prop=links&format=json&plnamespace=0&titles=Plato&pllimit=500";

With fetch we can turn the end point into a promise. Then we can use ChainedPromise to extend the promise:

import ChainedPromise from "chained-promise";

ChainedPromise.from(fetch(apiPoint))

First thing we want to do is to parse the resulting JSON:

  .flatMap((res) => res.json())

Now we have a promise that resolves into a JS object. Next we need to map the result into the format that ChainedPromise is expecting.

  .map((v) => {
    return {
      data: v.query.pages,
      next: v.continue ?
          fetch(apiPoint + '&plcontinue=' + encodeURIComponent(v.continue.plcontinue)) :
          {[ChainedPromise.DONE]: 'done fetching links from Plato page'}
    };
  })

The data field contains the material content of the value, while the next field contains either the promise to the next batch of data, or {[ChainedPromise.DONE]: lastNode} which ChainedPromise recognizes to be the terminal node.

Now that the chaining of the value has been configured, we can work on the series of data.

  .forEach((v) => {
    Object.keys(v.data).forEach((pageId) => {
      v.data[pageId].links.forEach((link) => {
        console.log(link.title);
      });
    });
  })

This executes the given callback function, and the result itself is a promise that resolves into the value of the terminal node when it reaches the end.

See the example project for the full example code. Also see jsdoc to ChainedPromise.ts for more explanation of other functions such as flatMap.

Disclaimer: This is not an official Google product.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.