Last active
October 30, 2020 14:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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