Given a recursive subroutine in single threaded environment which starts numerous asynchronous I/O operations and registers callback functions for each of them. This callbacks will be called on the completion of the operations.
Which ways are recommended to detect when all of the I/O operations are finished, in other words all of the callback have been called.
Since the code runs on a single thread, the most primitive solution would be to initialize a counter variable to 0, and increment this counter before every I/O operations and decrement it at tail of the callback functions. One can use events or actions (like in elm), however that solution would be very similar.
One possible optimization: if multiple I/O operation chained together (So one and only one I/O operation is started in the other I/O operations callback function), than it would be suffice to increment the counter at the beginning of the chain and decrement at the end of the chain, However one should aware the case when multiple I/O operation is started in one callback function, then all branch should be handled as a different chain.
Are there any more elegant way to handle this?