首页 > 解决方案 > 相当于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对象吗?如果是这样,怎么做?

标签: pythonpython-3.xtypescriptconcurrent.futures

解决方案


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())

推荐阅读