npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

flexlock-cb

v2.2.1

Published

A locking library like [`mutexify`](https://github.com/mafintosh/mutexify), [`mutex-js`](https://github.com/danielglennross/mutex-js), [`await-lock`](https://www.npmjs.com/package/await-lock), and [many more](https://www.npmjs.com/search?q=promise+lock),

Downloads

18

Readme

flexlock-cb

Build Status JavaScript Style Guide Maintainability Test Coverage

flexlock-cb is a very small, memory-concious, flexible locking library without dependencies but with typescript definitions (see in the bottom). Optimized even further than flexlock for the use with callbacks instead of promises.

npm i flexlock-cb --save

It is similar to other in-memory locking library like mutexify, mutex-js, await-lock, and many more, but with more flexibility in how to use it.

This makes it sturdier and more practical in many cases.

simple basic API

const { createLockCb } = require('flexlock-cb')

const lock = createLockCb()

lock(unlock => {
  // done before the next block
  unlock()
})
lock(unlock => {
  // will wait for the 
  unlock()
})

Propagation of errors and results to a callback

function callback (err, data) {
  // err === null
  // data === 'important'
}

lock(
  unlock => unlock(null, 'important'),
  callback
)

Promises are returned if no callback is added

const promise = lock(unlock => {
  unlock(null, 'important')
}) // Without passing in a callback, promises will be created

promise
  .catch(err => {})
  .then(data => {})
  // This way you can support both callback and promise based APIs

Timeouts in case anther lock never returns

function neverUnlock (unlock) { /* Due to a bug it never unlocks */ }
function neverCalled () {}

lock(neverUnlock)
lock(neverCalled, 500, err => {
  err.code === 'ETIMEOUT'
})

release handlers both once and for every release

function onEveryRelease () {}
function onNextRelease () {}

const lock = createLockCb(onEveryRelease) // Called everytime the lock is released
lock.released(onNextRelease) // Called next time the lock is released

await lock.released() // Promise API available as well

Like for Promises, two separate callbacks can be specified

function onSuccess (data) {}
function onError (err) {}

lock(unlock => unlock(), onSucess, onError)

sync handlers, for when you want to make sure that other locks are done

const lock = createLockCb()

const result = await lock.sync(() => {
  // no unlock function (automatically unlocked after method is done)
  return 123
})

result === 123 // the result is passed to the callback

In case you need it, a reference to the lock is also passed in:

const result = await lock.sync(lock => { /* ... */ })

Its also possible to wrap a method into a sync lock:

const fn = lock.syncWrap((foo, bar) => {
  /**
   - No unlock function.
   - Arguments are passed-through.
   - Executed will be asynchronously.
   - Return value will be ignored.
   */
  foo === 'hello'
  bar === 'world'
})
fn('hello', 'world')

Be aware that any errors that might occur will by-default result in uncaught exceptions!

You can handle those errors by passing an error handler when creating the lock:

const lock = createLockCb(null, err => {
  // Here you can handle any error, for example: emit('error', err)
})
const fn = lock.syncWrap(() => {
  throw new Error('error')
})

... or by adding a error handler directly when wrapping:

const fn2 = lock.syncWrap(() => {
  throw new Error('error')
}, err => {
  // Handle an error thrown in the sync-wrap
})

Destroying locks

When closing down an application you may want to also close all operations and prevent future operations:

import { createLockCb } from 'flexlock-cb'

const lock = createLockCb()
lock.destroy(new Error('lock destroyed') /* optional */)
try {
  lock(cb => {
    // will not be executed
  })
} catch (err) {
  // err ... will be the error passed-in to .destroy()
}

Typescript recommendation

Figuring out the proper typing was quite tricky for flexlock-cb. To make things easier for users, it exports a Callbacks type that can be used to reduce

import { Callbacks, createLockCb } from 'flexlock-cb'

const lock = createLockCb()

//
// Overloading for the two use cases (return type void or Promise)
// If you would like to improve this, vote for
// https://github.com/Microsoft/TypeScript/issues/29182
//
function fn (foo: string, bar: number, ...cb: Callbacks<string>): void
function fn (foo: string, bar: number): Promise<string>
function fn (foo: string, bar: number, ...cb) {
  return lock(() => `${foo} ${bar}`, 0, ...cb)
}

// Separate definitions with the support for timeouts
import { CallbacksWithTimeout } from 'flexlock-cb'

function fnTime (foo: string, bar: number, ...cb: CallbacksWithTimeout<string>): void
function fnTime (foo: string, bar: number, timeout?: number): Promise<string>
function fnTime (foo: string, bar: number, ...cb) {
  return lock(() => `${foo} ${bar}`, ...cb)
}

License

MIT