Created
September 21, 2010 20:20
-
-
Save evilkost/590454 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from tornado.ioloop import IOLoop | |
class CallbackDispatcher(object): | |
def __init__(self, generator): | |
self.ioloop = IOLoop.instance() | |
self.g = generator | |
try: | |
self.call(self.g.next()) | |
except StopIteration: | |
pass | |
def _send_result(self, results, single): | |
try: | |
result = results[0] if single else results | |
self.call(self.g.send(result)) | |
except StopIteration: | |
pass | |
def call(self, callers): | |
single = not hasattr(callers, '__iter__') | |
if single: | |
callers = [callers] | |
self.call_count = len(list(callers)) | |
results = [None] * self.call_count | |
if self.call_count == 0: | |
# 2. а надо так | |
#self._send_result(results, single) | |
self.ioloop.add_callback(partial(self._send_result, results, single)) | |
else: | |
for count, caller in enumerate(callers): | |
#1. сначала я этот вызов запихнул в ioloop.add_callback | |
# для одного вызова это какбы работало | |
# но ответы приходили в неправильном порядке и получалась чушь | |
caller(callback=partial(self.callback, results, count, single)) | |
def callback(self, results, index, single, arg): | |
self.call_count -= 1 | |
results[index] = arg | |
if self.call_count > 0: | |
return | |
# 2. а надо так | |
#self._send_result(results, single) | |
self.ioloop.add_callback(partial(self._send_result, results, single)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment