Skip to content

TryLockAsync

Asynchronously performs one immediate lock acquisition attempt.

1
$Cache.TryLockAsync(key: string):Promise<( string | `"null"` )>

Parameters

string key
    The shared lock key.

Returns

A promise containing the acquired token, or null when the key is already locked.

Remarks

This method does not wait for the lock to become available. Use $Cache.LockAsync when the script should wait for a limited time.

Performing work only when the lock is immediately available

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var tokenValue = await $Cache.TryLockAsync('mylock');
if (tokenValue == null) {
  // Another operation already holds the lock
} else {
  try {
    // Locked code block
  }
  finally {
    await $Cache.ReleaseLockAsync('mylock', tokenValue);
  }
}

Skipping duplicate background work when another script has already started it

1
2
3
4
5
6
7
8
9
var tokenValue = await $Cache.TryLockAsync('daily-summary');
if (tokenValue != null) {
  try {
    // Create the daily summary
  }
  finally {
    await $Cache.ReleaseLockAsync('daily-summary', tokenValue);
  }
}

See Also