Skip to content

add AbortController support to a cache of async requests

License

Notifications You must be signed in to change notification settings

GMOD/abortable-promise-cache

Repository files navigation

@gmod/abortable-promise-cache

NPM version Build Status

Adds AbortController/AbortSignal semantics to a cache of promises. Each get from the cache can optionally take an AbortSignal object that lets that request be aborted.

Cached fill requests will be aborted and evicted from the cache if all the incoming requests for it are aborted before the promise settles.

If the fill request has already settled before all the requests for it have been aborted, it will stay in the cache.

Install

$ npm install --save @gmod/abortable-promise-cache

Usage

import AbortablePromiseCache from '@gmod/abortable-promise-cache'
import QuickLRU from 'quick-lru'

const cache = new AbortablePromiseCache({
  // QuickLRU is a good backing cache to use, but you can use any
  // cache as long as it supports `get`, `set`, `delete`, and `keys`.
  cache: new QuickLRU({ maxSize: 1000 }),

  // the `fill` callback will be called for a cache miss
  async fill(requestData, abortSignal) {
    // do some long-running thing
    return longRunningThing(requestData, abortSignal)
  },
})

// Make a cached request. The returned promise will abort with the given abort signal if
// there is not already a cached copy that has been resolved.
// Fill requests will be signaled to abort if all the requests for them
// so far have been aborted.
const aborter = new AbortController()
const result = await cache.get('some key', { ...anyStuff }, aborter.signal)

// deleting and clearing will abort any outstanding requests
cache.delete('some key')
cache.clear()

API

Table of Contents

Academic Use

This package was written with funding from the NHGRI as part of the JBrowse project. If you use it in an academic project that you publish, please cite the most recent JBrowse paper, which will be linked from jbrowse.org.

License

MIT © Robert Buels

About

add AbortController support to a cache of async requests

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •