python - 相当于python中的js then()?
问题描述
在 Typescript 中,我习惯于编写这样的异步代码:
async function foo() // returns a promise
return new Promise<string>( resolve, reject) {
resolve('Hello!');
});
async function bar() {
s: string = await foo();
}
async function baz() {
foo().then((s: string) { alert(s); }
我将如何在 python (>= 3.7.0) 中执行此操作?我想这是正确的:
async def bar:
await s = foo()
但是和的python等价物foo()
呢baz()
?我将如何写它们?我应该使用concurrent.futures.Future对象吗?如果是这样,怎么做?
解决方案
Python async/await 语法看起来很像 ECMAScript async/await 语法。没有等效的.then()
,就像您不需要.then()
ES 中的 async/await 一样。
等效的异步 Python 代码将是(bar()
省略,因为它什么也没做):
import asyncio
async def foo():
return 'Hello!'
async def baz():
s = await foo()
print(s)
asyncio.run(baz())
推荐阅读
- java - 删除双向链表中给定位置的节点
- r - 为 igraph 中的每个顶点生成边权重列表
- java - JsonMappingException:未能延迟初始化角色集合
- hex - 将 ASCII 文本转换为 jpg 图像
- windows-10 - 使用 HTML Help Workshop 1.3 和 HTML5 和 Javascript DOM 并使用 HTML 帮助文件定位 Windows 10?
- javascript - HTML 向 PHP 提交表单,但需要使用 Javascript 进行一些解析
- visual-studio-app-center - Appcenter 管道工作正常,但现在无法构建
- tensorflow - 如何在张量流中对数组进行切片
- php - 从 PHP 中的 API 获取访问权限
- javascript - OpenLayers:我不能在事件侦听器之外获得 VectorSource 的功能吗?