是否可以在typescript中运行异步python脚本

2024-04-20 00:52:26 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我有一个python脚本,可以向微服务发出http请求。请求平均需要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()

我希望我的脚本能够继续与代码,并等待请求响应后类似的typescript。你知道吗

/**
 * 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();

基本上,我要寻找的是完成流程执行所需的时间和微服务的响应时间重叠,这样总的来说可以获得更好的响应时间。你知道吗


Tags: oftheto脚本logdataismain
1条回答
网友
1楼 · 发布于 2024-04-20 00:52:26

制作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绑定的,那么可以考虑使用asyncio的run_in_executor。你知道吗

相关问题 更多 >