我還沒有看到這些結構用得不多,但我發現自己寫他們使用異步電動機/等待在函數通常不會返回一個承諾,例如ES8立即調用異步函數表達式
chan.consume(queue, (msg) => {
this.pendingMsgs++; // executed immediately
(async() => {
await this.handleMessage(msg);
this.pendingMsgs--;
if (cancelled && this.pendingMsgs === 0) {
await chan.close();
await this.amqpConnectionPool.release(conn);
}
})();
});
,而不是
chan.consume(queue, async (msg) => { // external lib does not expect a return value from this callback
this.pendingMsgs++; // executed in promise context(?)
await this.handleMessage(msg);
this.pendingMsgs--;
if (cancelled && this.pendingMsgs === 0) {
await chan.close();
await this.amqpConnectionPool.release(conn);
}
});
或
chan.consume(queue, (msg) => {
this.pendingMsgs++; // no await - excess function decls & nesting
this.handleMessage(msg).then(() => {
this.pendingMsgs--;
if (cancelled && this.pendingMsgs === 0) {
chan.close().then(() => {
this.amqpConnectionPool.release(conn);
});
}
});
});
這是 '事'?我應該知道這裏有缺陷嗎? 在這種情況下使用異步/等待的內容是什麼?
什麼是這樣做的意義何在? – Pointy
@Pointy - 有沒有一些明顯的選擇我忽略了? –
@DrewR將返回值添加到當前不返回任何內容的函數不會違反任何替換原則。那麼爲什麼還要把所有東西都包裝在另一個函數和縮進層中呢? –