I need to implement function which involves long async operation (send request to external server and periodically check if it is done) which needs to behave like synchronous operation. I’m doing that following way:
start_long_operation()
while True:
if operation_finished():
return
sleep()
I wonder if this is a acceptable and if there is better solution?
Depending on the nature of the asynchronous operation, there are various existing solutions which will allow you to do this more elegantly. For example, if you’re waiting for a response from a server, you can use select on the socket to wait for a reply. You can also do this on several sockets at once.
Note: You should always use a timeout when possible to avoid waiting forever in case of some kind of error. The loop mentioned in your post suffers from this as well — you should limit the total time or the number of iterations.