Skip to content

Instantly share code, notes, and snippets.

@bsitruk
Created August 4, 2019 14:25
Show Gist options
  • Save bsitruk/c2498e63adfa60c0a92aa7068985b9ba to your computer and use it in GitHub Desktop.
Save bsitruk/c2498e63adfa60c0a92aa7068985b9ba to your computer and use it in GitHub Desktop.
Promise implementation using ThreadExecutor and Future in Python
from concurrent.futures import ThreadPoolExecutor, Executor, Future
class Promise:
def __init__(self, fn, *args, **kwargs):
self.fn = fn
self.callbacks = []
self.last_result = None
self.executor: Executor = ThreadPoolExecutor(max_workers=1)
self.future: Future = self.executor.submit(fn, *args, **kwargs)
self.future.add_done_callback(self._execute_callbacks)
def then(self, callback):
if self.future.done() and not self.callbacks:
result = self.last_result or self.future.result()
callback(result)
else:
self.callbacks.append(callback)
return self
def _execute_callbacks(self, future):
self.last_result = future.result()
while self.callbacks:
cb = self.callbacks.pop(0)
cb_res = cb(self.last_result)
self.last_result = cb_res or self.last_result
self.executor.shutdown(wait=False)
def wait_for_result(self):
return self.future.result()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment