Created
March 19, 2016 01:30
-
-
Save mayli/7795701b47eb1af83fa5 to your computer and use it in GitHub Desktop.
Promise in Python?
This file contains hidden or 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
#!/usr/bin/evn python2 | |
import json | |
import logging | |
logging.basicConfig(level=logging.DEBUG) | |
class Promise(object): | |
def __init__(self, function=lambda: None, prev=None): | |
super(Promise, self).__init__() | |
self.function = function | |
self.prev = prev | |
if not self.prev: | |
self.result = self.function() | |
else: | |
# evaluate prev and store as arg | |
self.result = self.function(self.prev.eval()) | |
class Then(object): | |
def __call__(then_self, then_function): | |
then_promise = Promise(function=then_function, prev=self) | |
return then_promise | |
self.then = Then() | |
def eval(self): | |
return self.result | |
def get(name): | |
return json.dumps({"Hello": name}) | |
def add_print(x): | |
logging.info("x = %s", x) | |
x += 1 | |
return x | |
Promise(lambda: get("noob")).then(json.loads).then(lambda response: response["Hello"]).then(logging.info) | |
Promise(lambda: 1).then(add_print).then(add_print).then(add_print).then(add_print) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment