這為將來添加了一個成功/錯誤處理程序,例如: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)))
添加回答
舉報
0/150
提交
取消