目前,我有一个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();
基本上,我寻找的是完成流程执行所需的时间和微服务的响应时间重叠,从而总体上允许更好的响应时间。
发布于 2019-05-31 07:47:30
使request_to_MS(url)
成为async def
协同例程,使用response = asyncio.create_task(request_to_MS(url))
将其作为任务进行调度。
它将开始执行。现在,您可以继续运行some_process()
。当您需要response
时,只需执行以下操作
do_something_with_response(await response)
编辑:只有当main也是一个async def
时,上述操作才有效,因为您只能在异步函数中使用await
s。调用asyncio.run(main())
,而不是调用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。
https://stackoverflow.com/questions/56386950
复制相似问题