Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Socket
Sign inDemoInstall

reuse-promise

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

reuse-promise

Reuse the same promise until resolved when retrieving it from a function


Version published
Weekly downloads
560
decreased by-39.78%
Maintainers
1
Weekly downloads
 
Created
Source

reuse-promise

build status npm version codeclimate

Purpose

When a function returns a promise and it's being called from multiple places in the app, new promises are being instantiated, and multiple async operations are be executed.

A common case is a function that gets an articleId and returns a promise that calls API. This function can be called from multiple places, each time will create a new promise and will issue a new request. This is usually not desired:

function findArticle(articleId) {
  return new Promise((resolve, reject) => {
    fetch(`/article/${articleId}`).then(r => r.json()).then(function (data) {
      resolve(data)
    })
  })
}

findArticle(1).then(article1 => console.log(article1)) // issues first request for articleId=1
findArticle(1).then(article1 => console.log(article1)) // issues second request for articleId=1
findArticle(2).then(article2 => console.log(article2)) // issues first request for articleId=2

reuse-promise decorates a function and temporary memoizes a promise until it's resolved. In this case, the first call for articleId=1 will create the new promise, issue the HTTP request, and remember that created promise for articleId=1. The second call with the same argument will return the same promise from earlier call.

Promises are kept in cache and returned without recreating a new one only while they are in progress. When the promise is resolved, it'll be cleared from this temporary cache, allowing a new call to findArticle(1) to recreate a promise and issue an HTTP request.

Promises are kept in an index by the arguments that were sent to the function, so findArticle(1) and findArticles([1, 2, 3]) will go through the original function and create a new promise, and any following call with the same arguments will reuse the same promise. The comparison between two sets of arguments is by JSON.stringify the argument array, hence a call with a new array [1, 2, 3] will still reuse the same promise.

Installation

npm install reuse-promise --save

Usage

reuse-promise can be used as a decorator in a class definition or as a wrapper to a function.

As a class decoartor

Requires babel and babel-plugin-transform-decorators-legacy plugin.

import { decorator as reusePromise } from 'reuse-promise'

class ArticleService {
  @reusePromise()
  find(articleId) {
    return new Promise((resolve, reject) => {
      fetch(`/article/${articleId}`).then(r => r.json()).then(function (data) {
        resolve(data)
      })
    })
  }
}

const articleService = new ArticleService()

articleService.find(1).then(article1 => console.log(article1)) // issues first request for articleId=1
articleService.find(1).then(article1 => console.log(article1)) // DOES NOT issue any request for articleId=1, will reuse the promise that was created in previous call
articleService.find(2).then(article2 => console.log(article2)) // issues first request for articleId=2

Wrapping a function

import reusePromise from 'reuse-promise'

function findArticle(articleId) {
  return new Promise((resolve, reject) => {
    fetch(`/article/${articleId}`).then(r => r.json()).then(function (data) {
      resolve(data)
    })
  })
}

const findArticleReusedPromise = reusePromise(findArticle)


findArticleReusedPromise(1).then(article1 => console.log(article1)) // issues first request for articleId=1
findArticleReusedPromise(1).then(article1 => console.log(article1)) // DOES NOT issue any request for articleId=1, will reuse the promise that was created in previous call
findArticleReusedPromise(2).then(article2 => console.log(article2)) // issues first request for articleId=2

option: memoize

reuse-promise can indefinitely remember the value that was returned from a promise, so no async code will execute more than once, even if the promise was previously resolved:

import { decorator as reusePromise } from 'reuse-promise'

class ArticleService {
  @reusePromise({ memoize: true })
  find(articleId) {
    return new Promise((resolve, reject) => {
      fetch(`/article/${articleId}`).then(r => r.json()).then(function (data) {
        resolve(data)
      })
    })
  }
}

const articleService = new ArticleService()

articleService.find(1).then(article1 => console.log(article1))

setTimeout(() => {
  // here, the original promise is resolved
  // without memoize: true, calling find(1) would go through original function and create a promise
  // however, with memoize the following call will be immediately resolved with the value

  articleService.find(1).then(article1 => console.log(article1))
}, 1000)

Test

npm install
npm test

License

MIT

Keywords

FAQs

Package last updated on 18 Apr 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc