Inconsistent Behavior When Acquiring Multiple Locks with Promise.all()
I have a use case where locking multiple list elements at once would be useful. For example, in a list of items that users check to add to a batch, we want to minimize overlap between different users' batches. Our implementation worked as expected when selecting items one at a time, but when using a "Select All" button, the behavior was inconsistent.
Specifically, when calling space.locks.acquire(id) inside a Promise.all() to acquire multiple locks asynchronously, not all requested locks were acquired. In my tests, only about half of the locks were successfully obtained, and there was no clear pattern in which ones were acquired.
After discussing this with @cameron-michie, they suggested posting an issue here and mentioned that the team may explore a new method for batch acquisition and release of locks.
Here’s a code example similar to what I tested:
const space = await spaces.get('space-name');
await space.enter({ name: 'test' });
const lockIds = ['section1', 'section2', 'section3'];
const lockAttributes = {
section1: { type: 'header' },
section2: { type: 'paragraph' },
section3: { type: 'footer' }
};
try {
const lockPromises = lockIds.map(id =>
space.locks.acquire(id, { attributes: lockAttributes[id] })
);
const acquiredLocks = await Promise.all(lockPromises);
console.log('All locks acquired successfully');
acquiredLocks.forEach(lock => {
console.log(`Lock acquired for ${lock.id} with status: ${lock.status}`);
});
} catch (error) {
console.error('Failed to acquire all locks:', error);
}
Thanks! 🙏🏻
Hi @bjornhansen, thanks for reporting this. I thought I'd start by trying to reproduce your issue. When I run your example code, I get the following:
All locks acquired successfully
Lock acquired for section1 with status: pending
Lock acquired for section2 with status: pending
Lock acquired for section3 with status: pending
Does this match what you're seeing?
Now when I run this jsfiddle (just add your ably keys/space names) it does appear to work as expected. All 50 locks seem to be acquired successfully. Unfortunately I no longer have the original code where I was having this issue so it may have been caused by something else.
More generally, is this Promise.all() approach the best practice way to do this?
More generally, is this
Promise.all()approach the best practice way to do this?
Currently, yes 🙂