是否可以以打字稿样式运行异步python脚本

时间:2019-05-30 23:39:47

标签: python python-3.x typescript asynchronous

目前,我有一个向微服务发出http请求的python脚本。该请求平均需要3秒。

这是我的python脚本摘要。

def main():
  response = request_to_MS(url)

  # This process does not need the response of the microservice.
  some_process()

  # This is where i actually need a response from the microservice
  do_something_with_response(response)


main()

我希望我的脚本能够继续执行代码,并稍后等待请求响应,类似于打字稿。

/**
 * I'd like to write this kind of code in python.
 */
function get_data(): Promise<string>{
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('This is resolved');
    })
  })
}

async function main(){
  const data = get_data();
  console.log('Data variable stores my promise ', data);
  // Some process
  [1, 2, 3, 4, 5, 6 ,7 ,8].forEach((x: number) => console.log(x));
  // I need the promise value here
  console.log('En el await', (await data).length)
}


void main();

基本上,我要寻找的是完成流程执行所需的时间和微服务的响应时间重叠,从而使总的响应时间更长。

1 个答案:

答案 0 :(得分:0)

使request_to_MS(url)async def成为例行程序,并与response = asyncio.create_task(request_to_MS(url))安排它作为任务。

它将开始执行。现在,您可以继续运行some_process()。当您需要response时,只需做

do_something_with_response(await response)

edit:仅当main也是async def时,以上内容才有效,因为您只能在异步函数中使用await。而不是呼叫main(),而是呼叫asyncio.run(main())

一起:

async def request_to_MS(url):
    await asyncio.sleep(3)
    return 'some internet data'

async def main():
    response = asyncio.create_task(request_to_MS(url))
    # response is now a Task

    some_process()

    # if response isn't done running yet, this line will block until it is
    do_something_with_response(await response)

asyncio.run(main())

一个重要的警告,some_process不必是协程,但是如果它是一个阻塞功能(通过CPU或IO),它将永远不会产生任何循环来使response运行。如果它通过IO阻止,则也考虑使其成为协程。如果没有异步支持它执行的任何低级IO操作,或者它受CPU限制,请考虑使用异步run_in_executor