Skip to content

Instantly share code, notes, and snippets.

@bossiernesto
Created December 15, 2021 01:22
Show Gist options
  • Save bossiernesto/2330d715a90d3ea0d28b43c9a8bf8eb0 to your computer and use it in GitHub Desktop.
Save bossiernesto/2330d715a90d3ea0d28b43c9a8bf8eb0 to your computer and use it in GitHub Desktop.
const randomDelay = () => new Promise(resolve =>
setTimeout(resolve, Math.random() * 100)
)
// Variable
let balance = 0
async function loadBalance () {
// delay in getting the load balance
await randomDelay()
return balance
}
async function saveBalance (value) {
// delay in saving the account balance
await randomDelay()
balance = value
}
async function withdraw () {
const balance = await loadBalance()
console.log(`balance loaded: ${balance}`)
const newBalance = balance + 50
await saveBalance(newBalance)
console.log(`withdraw - balance updated: ${newBalance}`)
}
async function deposit () {
const balance = await loadBalance()
console.log(`deposit - balance loaded: ${balance}`)
const newBalance = balance + 50
await saveBalance(newBalance)
console.log(`deposit - balance updated: ${newBalance}`)
}
async function main () {
const transaction1 = withdraw() // NOTE: no `await`
const transaction2 = deposit() // NOTE: no `await`
await transaction1 // awaiting here does not stop `transaction2`
// from being scheduled before transaction 1 is completed
await transaction2
const balance = await loadBalance()
console.log(`Final balance: ${balance}`)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment