Class AsyncLock

An async lock only runs 1 function at a time, this is useful if you have a series of async operations that depend on the computation of previous operation.

Example: An example could be changing a single field in a json object:

let storageBucket = script.createStorageVarJson<{ a: number, b: number }>("test_async_lock")
storageBucket.set({ a: 0, b: 0 })

async function badMutateField() {
// To change a single field we first need to retrieve the whole object
let currentValue = (await storageBucket.get())!.value

// Then we save it with a new value for the 'a' field
await storageBucket.set({ ...current, a: currentValue.a + 10 })

// But what happens if you run this function twice at the same time? Or if its changed somewhere else in the meantime?
// well it will be pretty random what happens then, it might sometimes work and it might sometimes not
}

// In fact just running it twice like this without awaiting (causing both promises to run in the background at the same time):
badMutateField()
badMutateField()
// Would create a bad result

// To fix this we create a async lock
const lock = new AsyncLock()

async function goodMutateField() {
// Then we use the withLocked method and give it a function to run
//
// This will produce the expected result of `a` being 20
// This is because AsyncLock only runs 1 function at a time
lock.withLocked(badMutateField)
lock.withLocked(badMutateField)
}

Constructors

Methods

Constructors

Methods

  • Run the provided function exclusively on the lock

    Type Parameters

    • T

    Parameters

    • cb: (() => T)
        • (): T
        • Returns T

    Returns Promise<Awaited<T>>

Generated using TypeDoc