Skip to content

Instantly share code, notes, and snippets.

@bossiernesto
Created December 15, 2021 01:22
Show Gist options
  • Select an option

  • Save bossiernesto/2330d715a90d3ea0d28b43c9a8bf8eb0 to your computer and use it in GitHub Desktop.

Select an option

Save bossiernesto/2330d715a90d3ea0d28b43c9a8bf8eb0 to your computer and use it in GitHub Desktop.

Revisions

  1. bossiernesto created this gist Dec 15, 2021.
    46 changes: 46 additions & 0 deletions simple_race_condition.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    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()