python:同步等待异步调用的回调结果

时间:2021-02-11 04:11:33

标签: python asynchronous callback

我必须对异步 API 进行一系列调用,它通过回调返回结果。 并且这些调用是连续的,下一个调用必须等到上一个调用完成。

我有这样的事情:

def main():

  value1 = None
  isFinished = False

  def _callback1(returned_value):
    nonlocal value1
    nonlocal isFinished 
    value1 = returned_value
    isFinished = True
  
  call_api_function_1(_callback1)
  
  timeout = 0
  while not isFinished or timeout < 10:
    sleep(1)
    timeout += 1
  
   # move on to next api call, repeating steps above

  value2 = None
  isFinished = False

  def _callback2(returned_value):
    nonlocal value2
    nonlocal isFinished 
    value2 = returned_value
    isFinished = True
  
  call_api_function_2(_callback2)
  
  timeout = 0
  while not isFinished or timeout < 10:
    sleep(1)
    timeout += 1

这看起来真的很丑,我该如何改进?我可能只重用一次 _callback 函数,还有什么?

0 个答案:

没有答案