Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to implement a simple lock to prevent an expensive promise from executing multiple times.
const expensiveOperation = () => new Promise((resolve) => {
console.log('Executing expensive operation')
setTimeout(resolve, 1000)
})
let expensiveOperationPromise = null
let expensiveOperationResult = null
const cacheExpensiveOperation = async () => {
if (expensiveOperationResult !== null) {
return expensiveOperationResult
}
if (expensiveOperationPromise !== null) {
return expensiveOperationPromise
}
expensiveOperationPromise = expensiveOperation() // no await here
expensiveOperationResult = await expensiveOperationPromise
expensiveOperationPromise = null
return expensiveOperationResult
}
// Prints "Executing expensive operation" only once.
Promise
.all([cacheExpensiveOperation(), cacheExpensiveOperation()])
.catch(console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment