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.

chained-promise's People

Contributors

chajath avatar gitter-badger avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chained-promise's Issues

Design and implement accumulation operation

This will accept an accumulation function of type {function(<U>, <V>) : Promise.<U>}, and turn ChainedPromise.<U> into ChainedPromise.<{data: V, next: ChainedPromise}>

This is an intermediate step in implementing reduce. A missing puzzle is how to support termination from ChainedPromise

Create .join() API to express joining operation

Functions such as .map() and .flatMap() can further be extended to provide an eDSL for easy data joining operation. For example, if we have a person's book records with books field having references to another API endpoints:

{
  "name": "John",
  "id": "12345",
  "books": [1277, 1255, 1290, 3003]
}

we want to be able to specify how to further join the refs. One possible way would be:

ChainedPromise.of(rq("/user/31337/books"))
    .join({books: [(v) => rq("/book/" + v)]})

This code should be equivalent to doing:

ChainedPromise.of(rq("/user/12345/books"))
    .flatMap((v) =>
      ChainedPromise.of(Promise.all(v.books.map((book) => rq("/books/" + book))))
          .map((books) => {
            v.books = books;
            return v;
          }));

Open questions:

  • Should we allow materializing join results in a different field?
  • Recursive joining operations?

Create callback function adapter for chained promise

The idea is to have the promise resolved once the callback function is called. For example, if we have a callback function defined as follows:

const cb = adaptedPromise.adaptToCallback();
someAsyncOp('abc','def', cb);

when someAsyncOp calls up on cb, adaptedPromise will be resolved into:

{
  data: [arg1, arg2, ...],
  next: nextPromise
}

nextPromise will be resolved next time cb is called upon.

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.