Simple promise lock.
yarn add p-lock
npm install p-lock
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"
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"
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;
};
Copyright 2013 - present © cnpmjs.org | Home |