亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JS 的 promise.then().catch() 的 python 任務等價物是什么?

JS 的 promise.then().catch() 的 python 任務等價物是什么?

慕哥9229398 2022-04-27 13:16:49
這為將來添加了一個成功/錯誤處理程序,例如: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):    passfor item of items:    send_coro = send(item)    send_task = asyncio.create_task(send_coro)    # ?????}
查看完整描述

1 回答

?
慕田峪9158850

TA貢獻1794條經驗 獲得超8個贊

如果我正確閱讀了 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 優雅,其中then并catch返回很好地鏈接的新期貨。


更好的方法是使用輔助協程來托管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)))


查看完整回答
反對 回復 2022-04-27
  • 1 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號