Promises acting synchronously
See original GitHub issueGreetings!
When it comes to promises, I hail from the land of AngularJS, which includes a few nice wrappers. I’ve only had to deal with pure promises a few times, so this issue is most likely me not understanding how to set this up (and there is a lack of basic examples in the README, instead directing readers to the spec)
This is the current code I have:
from promise import Promise
import urllib.request
url = 'https://jsonplaceholder.typicode.com/photos'
def success(data):
print("promise success!")
# print(data)
def reject(data):
print("rejected!")
print(data)
def getData(url):
def func(resolve, reject):
req = urllib.request.urlopen(url)
if req.getcode() == 200:
resolve(req.read())
else:
reject(Exception(req.getcode()))
return Promise(func)
print("getting resource")
p = getData(url)
p.then(success, reject)
print("Waiting on promise")
This seems to work synchronously: once getData()
is called, it returns a promise, but it also blocks execution. This is what the output looks like:
getting resource
promise success!
Waiting on promise
The order I was expecting:
getting resource
Waiting on promise
promise success!
I’ve also tested this with a simple time.sleep(5)
and resolving immediately after that. Again, once getData()
is run, it simply sleeps for 5 seconds without hitting the “Waiting” print, then continues onword.
Sorry if this is a bit of an obtuse question, I acknowledge I’m probably not working with it correctly, but I can’t seem to figure it out.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:10 (1 by maintainers)
Top GitHub Comments
Hi! I’ve just tried a variant of your code example with time measuring and multiple promises locally and… it really doesn’t work (python 3.6):
Bug 1:
Promise(func)
executes immediately and blocks main thread, whatever the scheduler.Bug 2:
Promise.promisify(func)
returns a function, not a promise.With ThreadScheduler:
My full code:
I was able to get it work as async promises with a really ugly syntax:
I’m having trouble with my DataLoader queueing things. It seems to load the data immediately when I call
load()
instead of waiting.