Aug-17-2017, 08:44 PM
This all seems kinda crazy, so here's some more info. Almost all code would be consumers of a promise, only a library would implement one. The important part is that the code generating a promise should have a little bit of setup, but otherwise immediately return, and use the callbacks to signal when it's done doing it's work.
Here's a sample use case, using a delayed timer with a callback, that gets called after that delay:
Here's a sample use case, using a delayed timer with a callback, that gets called after that delay:
from promise import Promise import threading import time def delayed(delay): def runner(resolved, failed): def thread(): time.sleep(delay) resolved() threading.Thread(target=thread).start() return Promise(runner) if __name__ == "__main__": def callback(*args): print("Inside callback") print("Before delayed callback") delayed(2.5).then(callback) print("After delayed callback") for _ in range(5): print("waiting...") time.sleep(1)
Output:Before delayed callback
After delayed callback
waiting...
waiting...
waiting...
Inside callback
waiting...
waiting...