async-mutex#tryAcquire TypeScript Examples
The following examples show how to use
async-mutex#tryAcquire.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: revision_cache.ts From skynet-js with MIT License | 6 votes |
/**
* Calls `exclusiveFn` with exclusive access to the given cached entry. The
* revision number of the entry can be safely updated in `exclusiveFn`.
*
* @param publicKey - The given public key.
* @param dataKey - The given data key.
* @param exclusiveFn - A function to call with exclusive access to the given cached entry.
* @returns - A promise containing the result of calling `exclusiveFn`.
*/
async withCachedEntryLock<T>(
publicKey: string,
dataKey: string,
exclusiveFn: (cachedRevisionEntry: CachedRevisionNumber) => Promise<T>
): Promise<T> {
// Safely get or create mutex for the requested entry.
const cachedRevisionEntry = await this.getRevisionAndMutexForEntry(publicKey, dataKey);
try {
return await tryAcquire(cachedRevisionEntry.mutex).runExclusive(async () => exclusiveFn(cachedRevisionEntry));
} catch (e) {
// Change mutex error to be more descriptive and user-friendly.
if ((e as Error).message.includes("mutex already locked")) {
throw new Error(
`Concurrent access prevented in SkyDB for entry { publicKey: ${publicKey}, dataKey: ${dataKey} }`
);
} else {
throw e;
}
}
}