AniUI Academy
hard+350 XPPractice

Serialise work per key

A shared lock over all writes is simple and slow: saving document A blocks saving document B for no reason. What you usually want is one lock per record.

Implement createKeyedLock(), returning a function run(key, task). task takes no arguments and returns a promise, and run returns a promise settling with that task's own result. Tasks sharing a key run one at a time, in the order run was called for that key, and a task never starts before the previous task for its key has settled. Tasks with different keys are independent and run concurrently. If a task rejects, only its own promise rejects — the next task for that key still runs.

What it has to do

  • Never run two tasks with the same key at the same time.
  • Start same-key tasks in call order.
  • Let different keys run concurrently.
  • Settle each run with its own task's result.
  • Keep the key's queue moving after a task rejects.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.