【问题标题】:Python 3.6.9 twisted: How to await async function to return x, then continuePython 3.6.9 扭曲:如何等待异步函数返回 x,然后继续
【发布时间】:2020-05-22 10:03:43
【问题描述】:

我需要用 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()

显然这可以通过 await 和 deferreds 来实现,但我无法让它工作。这里的根本问题是 API_response 将始终返回 x 和 y,但顺序取决于情况。因此等待直到 API_response() == x

【问题讨论】:

  • 伪伪代码使您很难遵循您正在尝试做的事情。我不确定您所说的“触发器”是什么意思。这与“通话”有什么不同?我会大胆猜测答案,但您可能需要考虑熟悉 sscce.orgstackoverflow.com/help/how-to-ask

标签: python async-await twisted deferred


【解决方案1】:

您可能对 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 循环可能会有什么帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多