【问题标题】:What's python's Task equivalent of a JS' promise.then().catch() without await?没有等待的 JS 的 promise.then().catch() 的 python 任务等价物是什么?
【发布时间】:2019-12-16 08:27:00
【问题描述】:

这会为将来添加一个成功/错误处理程序,例如:

async function send(item) {
    // ...
}

for (const item of items) {
    const sendPromise = send(item);
    sendPromise
        .then(x => console.log(x))
        .catch(x => console.error(x))
}

而不是等待:

for (const item of items) {
    const sendPromise = send(item);
    try {
        const x = await sendPromise
        console.log(x)
    } catch (e) {
        console.error(e)
    }
}

什么是 python 的 Task 相当于 JS 的 promise.then() 没有等待?

async def send(item):
    pass

for item of items:
    send_coro = send(item)
    send_task = asyncio.create_task(send_coro)
    # ?????
}

【问题讨论】:

    标签: python promise async-await python-asyncio coroutine


    【解决方案1】:

    如果我正确读取了 JavaScript,它会为将来添加一个错误处理程序。直译应该是这样的:

    def _log_err(fut):
        if fut.exception() is not None:
            print(f'error: {fut.exception()}')
    
    for item in items:
        send_future = asyncio.create_task(send(item))
        send_future.add_done_callback(_log_err)
    

    请注意,上面不是惯用的,因为它诉诸回调并且不如原始 JavaScript 优雅,其中 thencatch 返回很好地链接的新期货。

    更好的方法是使用辅助协程来托管await。这不需要外部函数为async def,因此等价于上述:

    async def _log_err(aw):
        try:
            return await aw
        except Exception as e:
            print(f'error: {e}')
    
    for item in items:
        asyncio.create_task(_log_err(send(item)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-01
      • 2019-04-04
      • 2011-09-03
      • 2011-03-07
      • 2013-10-18
      • 2019-04-02
      • 2012-03-20
      • 1970-01-01
      相关资源
      最近更新 更多