p-lock
Simple promise lock
Last updated 5 years ago by bconnorwhite .
MIT · Repository · Original npm · Tarball · package.json
$ cnpm install p-lock 
SYNC missed versions from official npm registry.

p-lock

NPM TypeScript Coverage Status GitHub Stars Twitter Follow

Simple promise lock.

Installation

yarn add p-lock
npm install p-lock

API

Usage

import { writeFile } from "fs";
import { getLock } from "p-lock";

const lock = getLock();

lock("file").then((release) => {
  setTimeout(() => {
    writeFile("test.txt", "hello", () => {
      release();
    });
  }, 1000);
});

lock("file").then((release) => {
  writeFile("test.txt", "world", () => {
    release();
  });
});

// contents of test.txt will be "world"

Replace

Reject and replace any promises waiting for the lock, rather than resolving each in series.

import { writeFile } from "fs";
import { getLock } from "p-lock";

const lock = getLock({ replace: true });

let writeCounter = 0;

lock("file").then((release) => {
  setTimeout(() => {
    writeCounter += 1;
    writeFile("test.txt", `update #${writeCounter}`, () => {
      release();
    });
  }, 1000);
});

lock("file").then((release) => {
  writeCounter += 1;
  writeFile("test.txt", `update #${writeCounter}`, () => {
    release();
  });
}).catch(() => {
  // This promise will reject, since the next one replaces.
});

lock("file").then((release) => {
  writeCounter += 1;
  writeFile("test.txt", `update #${writeCounter}`, () => {
    release();
  });
});

// contents of test.txt will be "update #2"

Types

import { getLock, LockOptions } from "p-lock";

function getLock(): Lock;

type Lock = (key?: string) => Promise<ReleaseFn>;

type ReleaseFn = () => void;

type LockOptions = {
  /**
   * When aquiring a lock for some key, replace first promise in line rather than adding to queue.
   * Replaced promise will be rejected.
   * Default: `false`
   */
  replace?: boolean;
};

Dev DependenciesDavid


License license

MIT

Current Tags

  • 2.1.0                                ...           latest (5 years ago)

3 Versions

  • 2.1.0                                ...           5 years ago
  • 2.0.0                                ...           5 years ago
  • 1.0.0                                ...           5 years ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 1
Dependencies (0)
None
Dev Dependencies (1)

Copyright 2013 - present © cnpmjs.org | Home |