Promisified thunk with caching (pronounced "funky")

Overview

phunky

npm package npm downloads

phunky (promisified thunk, pronounced funky) is yet another thunk-inspired library, to delay a calculation until its result is needed, but also cache the result

You can provide a max age for the cache, so it automatically resolves your function again when stale, or force a new value at any time

🎉 You can customise the behaviour of your Phunk, perhaps immediately resolve, or choose to cache rejections, very funky!

🐐 Being promise-based, you can await the result of your function inline

💯 Test coverage

Getting started

Importing

// esm
import { Phunk } from 'phunky'

// cjs
const { Phunk } = require('phunky')

Example usage

import { Phunk } from 'phunky'

let counter = 0

const getNextCounter = async () => {
  counter += 1
  return counter
}

const counterCache = new Phunk(getNextCounter)

console.log(await counterCache.current()) // 1
console.log(await counterCache.current()) // 1
console.log(await counterCache.next()) // 2
console.log(await counterCache.next()) // 3
console.log(await counterCache.current()) // 3

Cache auto-refresh

Setting a ttl (time-to-live) will allow your function to automatically be re-invoked if the value is considered stale. Great for caching access tokens, or any values that can be time-expensive to refresh on every operation.

let counter = 0

const getNextCounter = async () => {
  counter += 1
  return counter
}

const counterCache = new Phunk(getNextCounter, { ttl: 1000 })

console.log(await counterCache.current()) // 1
// wait at least 1 second
console.log(await counterCache.current()) // 2

Resolution status

If you have a long-running function to execute, you can always inspect the status using the following helper methods

  • isResolving will return true if your function is running
  • isResolved will return true if your function completed without throwing
  • isRejected will return true if your function threw an error
const myThunk = new Phunk(async () => { /* Some long process */ })

myThunk.next() // if you don't await the result then:
console.log(myThunk.isResolving()) // true
console.log(myThunk.isResolved()) // false
console.log(myThunk.isRejected()) // false

Configuration

Optionally pass a configuration object as a second argument to the constructor, with the following options

  • init: Optional, defaults to false, set to true to immediately invoke your function and have the result ready for when you first call .current().
  • cacheRejections: Optional, defaults to false, set to true for your Phunky instance to cache any errors that are thrown by your function. If false, calling .current() will try re-invoking your function if it previously rejected.
  • ttl: (time-to-live) Optional. If set, it must be a positive integer for the number of milliseconds resolved values should live for. Any calls to .current() after that time, will automatically re-invoke your function to get an updated value.

Class methods

  • current(): Returns a promise of the result of the previous invocation of your function, or will await the result of the next invocation of your function if it has not previously been invoked or other criteria are met, see cacheRejections and ttl config options.
  • next(): Returns a promise of the result of the next invocation of your function.
  • isResolving(): Returns a boolean of whether your function is currently being invoked.
  • isResolved(): Returns a boolean of whether your function previously resolved without error. Will always return false if isResolving() returns true.
  • isRejected(): Returns a boolean of whether your function previously rejected with an error. Will always return false if isResolving() returns true.
You might also like...

🚀 A well-structured boilerplate and Starter for Next.js 12+, Tailwind CSS 3, Redux, Redux Thunk, and TypeScript

🚀 A well-structured boilerplate and Starter for Next.js 12+, Tailwind CSS 3, Redux, Redux Thunk, and TypeScript ⚡️ Made with developer experience first ESLint + Prettier + Lint-Staged + VSCode setup

Nov 28, 2022

Given an object and a property, replaces a property descriptor (or deletes it), and returns a thunk to restore it.

Given an object and a property, replaces a property descriptor (or deletes it), and returns a thunk to restore it.

Given an object and a property, replaces a property descriptor (or deletes it), and returns a thunk to restore it.

Apr 20, 2022

Pebble - A free funky formalicious icon set for React (& plain ol' SVG & PNG)

Pebble - A free funky formalicious icon set for React (& plain ol' SVG & PNG)

A free funky formalicious icon set for React (& plain ol' SVG & PNG) Pebble is an icon set that aims for a friendly character. There's no real

Nov 19, 2022

Enhanced interval features for Node.js, such as promisified interval and human readable time parsing.

Interval-next Interval-next is a package that extends Javascript's built-in setInterval() capabilities. You have a plain and promisified interval meth

Jul 28, 2022

Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all with IndexedDB. Perfectly suitable for your next (PWA) app.

Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all with IndexedDB. Perfectly suitable for your next (PWA) app.

BrowstorJS 🚀 💾 🔒 Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all

Aug 5, 2022

Type-safe and Promisified API for Web Worker and Iframe

💛 You can help the author become a full-time open-source maintainer by sponsoring him on GitHub. typed-worker Install npm i typed-worker Usage Create

Dec 31, 2022

:zap: RAN! React . GraphQL . Next.js Toolkit :zap: - SEO-Ready, Production-Ready, SSR, Hot-Reload, CSS-in-JS, Caching, CLI commands and more...

:zap: RAN! React . GraphQL . Next.js Toolkit :zap: - SEO-Ready, Production-Ready, SSR, Hot-Reload, CSS-in-JS, Caching, CLI commands and more...

RAN : React . GraphQL . Next.js Toolkit New version is coming... Follow up here: https://github.com/Sly777/ran/issues/677 Features Hot-Reload Ready fo

Jan 3, 2023

⚛️ Hooks for fetching, caching and updating asynchronous data in React

⚛️ Hooks for fetching, caching and updating asynchronous data in React

Hooks for fetching, caching and updating asynchronous data in React Enjoy this library? Try the entire TanStack! React Table, React Form, React Charts

Jan 9, 2023

⚛️ Hooks for fetching, caching and updating asynchronous data in React

⚛️ Hooks for fetching, caching and updating asynchronous data in React

Hooks for fetching, caching and updating asynchronous data in React Enjoy this library? Try the entire TanStack! React Table, React Form, React Charts

Dec 31, 2022

A script and resource loader for caching & loading files with localStorage

A script and resource loader for caching & loading files with localStorage

Basket.js is a script and resource loader for caching and loading scripts using localStorage ##Introduction for the Non-Developer Modern web applicati

Dec 30, 2022

SSHOT is a ✨ Web Screenshot API ✨ with caching kept in mind!

SSHOT is a ✨ Web Screenshot API ✨ with caching kept in mind!

label icon Quick Start rocket Welcome to SSHOT (/s:shot/) SSHOT is a ✨ Web Screenshot API ✨ with caching kept in mind! Just pass in the parameters for

Dec 24, 2022

Allo Caching for Deno

Simple caching solution in Typescript.

Feb 14, 2022

This library helps implement caching using Cloudflare Workers KV

With a few lines of code, you can control the execution of functions that you want to cache for speed, store them in the cache, and skip execution of the function if the cache exists.

Oct 20, 2022

🪐 The IPFS gateway for NFT.Storage is not "another gateway", but a caching layer for NFTs that sits on top of existing IPFS public gateways.

nftstorage.link The IPFS gateway for nft.storage is not "another gateway", but a caching layer for NFT’s that sits on top of existing IPFS public gate

Dec 19, 2022

A fast, safe and easy caching mechanism similar to Redis written in typescript

Viper Viper is a memory based caching mechanism which is aimed towards ease of use and speed. It's in a very early stage right now and not meant to us

Jan 24, 2022

A caching middeware library for Deno HTTP framework, Oak.

A caching middeware library for Deno HTTP framework, Oak.

Caching middleware library for Oak Table of Contents Description Getting Started Middleware and caching Authors License Description Zoic is an easy-to

Sep 28, 2022

Next-level mongoose caching layer with event based cache clearing

SpeedGoose ## About The Project This project is a next-level mongoose caching library which is fully written in typescript. It's caching on two levels

Dec 15, 2022

Skip a job if it already succeeded for the same repo state. Uses S3 for caching.

Skip a job if it already succeeded for the same repo state. Uses S3 for caching.

🪣 ♻️ S3 Cache Action First Run, Cold Cache Next Run, Cache Hit Description Allows to skip a job if it already succeeded for the same repo state. Uses

Jul 22, 2022
Releases(v1.1.0)
  • v1.1.0(Nov 6, 2022)

  • v1.0.0(Oct 15, 2022)

  • v0.2.1-beta(Oct 11, 2022)

    Full Changelog: https://github.com/mupperton/phunky/compare/v0.2.0-beta...v0.2.1-beta

    Fixes

    • Fixed typings for promises, no longer have return types of Promise<Promise<T>> (425e3ed)
    Source code(tar.gz)
    Source code(zip)
  • v0.2.0-beta(Oct 11, 2022)

    Full Changelog: https://github.com/mupperton/phunky/compare/v0.1.0-alpha...v0.2.0-beta

    Features

    • Added ttl config option to automatically re-invoke your function if it is considered stale (ad7bfde)

    Documentation

    • Added documentation of the config options and class methods for Phunk (50dd6b7)
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0-alpha(Oct 10, 2022)

Enhanced interval features for Node.js, such as promisified interval and human readable time parsing.

Interval-next Interval-next is a package that extends Javascript's built-in setInterval() capabilities. You have a plain and promisified interval meth

Snowy 5 Jul 28, 2022
Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all with IndexedDB. Perfectly suitable for your next (PWA) app.

BrowstorJS ?? ?? ?? Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all

Nullix 8 Aug 5, 2022
Allo Caching for Deno

Simple caching solution in Typescript.

Adam Josefus 5 Feb 14, 2022
🪐 The IPFS gateway for NFT.Storage is not "another gateway", but a caching layer for NFTs that sits on top of existing IPFS public gateways.

nftstorage.link The IPFS gateway for nft.storage is not "another gateway", but a caching layer for NFT’s that sits on top of existing IPFS public gate

NFT.Storage 37 Dec 19, 2022
A fast, safe and easy caching mechanism similar to Redis written in typescript

Viper Viper is a memory based caching mechanism which is aimed towards ease of use and speed. It's in a very early stage right now and not meant to us

Japroz Saini 1 Jan 24, 2022
A caching middeware library for Deno HTTP framework, Oak.

Caching middleware library for Oak Table of Contents Description Getting Started Middleware and caching Authors License Description Zoic is an easy-to

OSLabs Beta 64 Sep 28, 2022
Next-level mongoose caching layer with event based cache clearing

SpeedGoose ## About The Project This project is a next-level mongoose caching library which is fully written in typescript. It's caching on two levels

Arkadiusz Gil 17 Dec 15, 2022
Skip a job if it already succeeded for the same repo state. Uses S3 for caching.

?? ♻️ S3 Cache Action First Run, Cold Cache Next Run, Cache Hit Description Allows to skip a job if it already succeeded for the same repo state. Uses

Pleo Open Source 8 Jul 22, 2022
Cache is easy to use data caching Node.js package. It supports Memcached, Redis, and In-Memory caching engines.

Cache Cache NPM implements wrapper over multiple caching engines - Memcached, Redis and In-memory (use with single threaded process in development mod

PLG Works 49 Oct 24, 2022
Funkytooltips - A jQuery plugin to create funky tooltips

Funkytooltips Funkytooltips is a jQuery plugin to generate tooltips based on the data contained in HTML tags. Installation The plugin can be installed

Nourdine 0 Apr 17, 2021