[Ethereum] When watching events using web3, does .stopWatching() block the code running

eventsweb3js

this is a sample code in web3 document :

var myEvent = myContractInstance.MyEvent({some: 'args'}, {fromBlock: 0, toBlock: 'latest'});

myEvent.watch(function(error, result){

});

myEvent.stopWatching();

// extra code to run

The first and second line will have all matching events to undergo the callback function, asynchronously.

If there is more code to run, does stopWatching() method wait until all events complete their callback functions, or do the callback functions run parallel with the extra code?

Best Answer

This looks to me like a race condition.

The watch callback is executed asynchronously when data matching your filter is polled from the node. Calling myEvent.watch is non-blocking and as such myEvent.stopWatching() will be called immediately afterwards.

The result you will get depends on whether the polling completes in the milliseconds before stopWatching is called.

This is non-deterministic - you might get different results each time you run it.

Related Topic