目前,我有一个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();
基本上,我要寻找的是完成流程执行所需的时间和微服务的响应时间重叠,这样总的来说可以获得更好的响应时间。你知道吗
制作
request_to_MS(url)
一个async def
联合例程,将它作为一个任务与response = asyncio.create_task(request_to_MS(url))
一起调度。你知道吗它将开始执行。现在您可以继续运行
some_process()
。当您需要response
时,只需edit:只有main也是
async def
时,上面的方法才有效,因为您只能在异步函数中使用await
。与其调用main()
,不如调用asyncio.run(main())
。你知道吗总共:
一个重要的警告是,
some_process
不一定是一个协程,但是如果它是一个阻塞函数(由CPU或IO执行),它将永远不会产生任何让response
运行的周期。如果它通过IO阻塞,也可以考虑将其作为一个协同程序。如果对它执行的任何低级IO操作都没有异步支持,或者它是CPU绑定的,那么可以考虑使用asyncio的run_in_executor。你知道吗相关问题 更多 >
编程相关推荐