Skip to content
This repository has been archived by the owner on Jun 14, 2018. It is now read-only.

When not to use synchronized transactions, and how to do it

Tim Coulter edited this page Jun 24, 2015 · 1 revision

Sometimes you might want to make multiple transactions at once, and wait for them all to complete. If you use the default behavior however (shown below), you'll notice that your app will wait unnecessarily long as Pudding ensures each transaction is processed before the next one continues:

coin = MetaCoin.at(contract_address, {gasLimit: 3141592, from: account_one})

coin.sendCoin(account_two, 2).then (tx) ->
  # Pudding will wait for this tx to be processed before running 
  # this code block.
  coin.sendCoin(account_three, 3)
.then (tx) ->
  # ... and it will wait for this tx...
  coin.sendCoin(account_four, 4)
.then (tx) ->
  # ... and this tx...
  coin.sendCoin(account_five, 5)
.then (tx) ->
  # ... and this tx before finally completing.
  done() 

The above code effectively puts each transaction on its own network block. With an average block time of 12 seconds, that's a long time to wait.

The way around that is to use the sendTransaction() function on all transaction methods but the last. sendTransaction() is not synchronized with the network, and so will add the transaction to the network and call its callback (if specified) immediately. Here we don't pass a callback as we don't usually use the transaction object anyway:

coin.sendCoin.sendTransaction(account_two, 2)
coin.sendCoin.sendTransaction(account_three, 3)
coin.sendCoin.sendTransaction(account_four, 4)

# Only wait on the last transaction added to the network.
coin.sendCoin(account_five, 5).then (tx) ->
  done() 

In this case all four transactions are added to the same network block, and we only had to wait a quarter of the time for all transactions to complete.

CAUTION: In this example, all parallel transactions are independent of each other. If each transaction depends on the previous one, you likely won't see the behavior you expect.