Implement the Web Locks API: exclusive and shared modes, ifAvailable, steal, AbortSignal and query()

hardAbout 55 minutesUpdated CodingProjavascriptweb-lockslocksabortsignalpromisespolyfills
Not solved

Share this question

Problem

navigator.locks.request(name, callback) coordinates work across tabs and workers of one origin: only one tab refreshes the auth token, only one tab owns the WebSocket, a migration runs once. The lock is held while the callback's promise is pending. Build the same API in memory, following the Web Locks specification, as createLockManager({ clientId = "client-1" } = {}), which returns { request, query }.

const locks = createLockManager();
await locks.request("token-refresh", async () => {
  const token = await refreshToken(); // other tabs wait here
  save(token);
});
const result = await locks.request("leader", { ifAvailable: true }, (lock) => (lock ? "I lead" : "someone else leads"));

Ref. UR-1443 · © UIRound · uiround.com/questions/implement-the-web-locks-api-exclusive-and-shared-modes-ifavailable-steal-abortsignal-and-query

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment