Skip to content

Instantly share code, notes, and snippets.

@pavelkucera
Last active October 30, 2020 14:59
Show Gist options
  • Save pavelkucera/453acf622dc3cad29455ef93ccf49c23 to your computer and use it in GitHub Desktop.
Save pavelkucera/453acf622dc3cad29455ef93ccf49c23 to your computer and use it in GitHub Desktop.
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