dab0bby
dab0bby

Reputation: 3001

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!

Upvotes: 0

Views: 208

Answers (1)

Ben Darnell
Ben Darnell

Reputation: 22134

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

Upvotes: 2

Related Questions