我需要使用Twisted运行python 3.6.9。
我有一个函数,需要等待异步事件返回一定的值才能继续。此异步事件始终返回此值,但是可能需要一些时间。
最终,我想这样做(伪代码示例):
def API_response(msg):
if msg == 'hello':
return x
if msg == 'world':
return y
def do_stuff():
print('I need API to say hello to me')
do something that triggers API_response
await until API_response() == x
print('success!')
start socket managers
run socket managers which will eventually trigger do_stuff()
显然,这可以通过等待和延迟来实现,但是我无法使其正常工作。这里的潜在问题是API_response将始终返回x和y,但是顺序取决于情况。因此,等待直到API_response()== x
您可能对while循环感兴趣:
def do_stuff():
print('I need API to say hello to me')
do something that triggers API_response
while await until API_response() != x:
# Delay until you think API_response might be different
print('success!')
当然,此代码比问题中的代码更有效。我假设有一些有效的原始代码可以用相同的方式进行转换,并且仅编辑了此伪伪代码以显示while
循环可能会有所帮助。