import { IMQLock, AcquiredLock } from'.';
asyncfunctiondoSomething(): Promise<number | AcquiredLock<number>> {
const lock: AcquiredLock<number> = await IMQLock.acquire<number>('doSomething');
if (IMQLock.locked('doSomething')) {
// avoiding err handling in this way can cause ded-locks// so it is good always try catch locked calls!// BTW, IMQLock uses timeouts to avoid dead-lockstry {
// this code will be called only once per multiple async calls// so all promises will be resolved with the same valueconst res = Math.random();
IMQLock.release('doSomething', res);
return res;
}
catch (err) {
// release acquired locks with error
IMQLock.release('doSomething', null, err);
throw err;
}
}
return lock;
}
(async () => {
for (let i = 0; i < 10; ++i) {
// run doSomething() asynchronously 10 times
doSomething().then((res) =>console.log(res));
}
})();
Class IMQLock. Implements promise-based locks.
import { IMQLock, AcquiredLock } from '.'; async function doSomething(): Promise<number | AcquiredLock<number>> { const lock: AcquiredLock<number> = await IMQLock.acquire<number>('doSomething'); if (IMQLock.locked('doSomething')) { // avoiding err handling in this way can cause ded-locks // so it is good always try catch locked calls! // BTW, IMQLock uses timeouts to avoid dead-locks try { // this code will be called only once per multiple async calls // so all promises will be resolved with the same value const res = Math.random(); IMQLock.release('doSomething', res); return res; } catch (err) { // release acquired locks with error IMQLock.release('doSomething', null, err); throw err; } } return lock; } (async () => { for (let i = 0; i < 10; ++i) { // run doSomething() asynchronously 10 times doSomething().then((res) => console.log(res)); } })();