Skip to content

Instantly share code, notes, and snippets.

Last active October 30, 2020 14:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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.
.all([cacheExpensiveOperation(), cacheExpensiveOperation()])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment