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:
asyncfunctionbadMutateField() { // To change a single field we first need to retrieve the whole object letcurrentValue = (awaitstorageBucket.get())!.value
// Then we save it with a new value for the 'a' field awaitstorageBucket.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 constlock = newAsyncLock()
asyncfunctiongoodMutateField() { // 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) }
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: