Search code examples
pythonasynchronoustornado

How start multiple tasks at once in tornado


I have a for .. in .. : loop, that is calling a methond an waiting for the result. How can I make this loop to start all at once and then wait for the results?

This is my code:

@gen.coroutine
def update_all( self ):
    for service in self.port_list:
        response = yield self.update_service( str( service.get( 'port' ) ) )
        self.response_list.append( response )

    self.response = json.dumps( self.response_list )

    return self.response

Thank you!


Solution

  • Build a list (of Future objects returned by update_service()), and then yield the list:

    @gen.coroutine
    def update_all( self ):
    
        futures = []
        for service in self.port_list:
            futures.append(self.update_service(str(service.get('port'))))
    
        self.response_list = yield futures
        self.response = json.dumps( self.response_list )
    
        return self.response