编程语言
首页 > 编程语言> > javascript – ES8立即调用异步函数表达式

javascript – ES8立即调用异步函数表达式

作者:互联网

我没有看到这些构造使用太多,但我发现自己编写它们以在通常不会返回promise的函数中使用async / await,例如

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);
       });
    }
  });
});

这是’一件事’吗?我应该注意到这里有陷阱吗?
在这种情况下,async / await的使用是什么?

解决方法:

Is this ‘a thing’?

是.它偶尔出现,例如, here.他们被称为IIAFEs

标签:ecmascript-2017,javascript,async-await
来源: https://codeday.me/bug/20191001/1837465.html