【问题标题】:Continue execution with async/await使用 async/await 继续执行
【发布时间】:2019-05-24 05:46:58
【问题描述】:

大部分文章都提到await 是then 的替代品。但是,我找不到使用await 执行以下方法的方法,因为它将推迟执行直到run query 完成。只是好奇,有没有办法?

this.database
    .run(query, bindings)
    .then(result => this.ws.send(result))
    .catch(err => this.ws.error(err));
return reply.code(202).send();

【问题讨论】:

标签: javascript node.js promise async-await


【解决方案1】:

您不能在此处直接使用 async/await 的事实应该提示您,您在这里所拥有的并不是一个好主意。这是一劳永逸的代码,这很少是一种好的做法。

但是,如果这确实是您想要做的,一个可用的选择是将 async/await 放在单独的方法中。

分离方法:

async runQuery(query, bindings) {
    try {
        const result = await this.database.run(query, bindings);

        await this.ws.send(result);
    } catch(err) {
        await this.ws.error(err);
    }
}

主要代码:

this.runQuery(query, bindings);

return reply.code(202).send();

【讨论】:

  • 感谢您的建议。我让它一劳永逸,因为我不知道查询执行需要多长时间。有什么替代建议吗?
  • @Cemre 如果您想要即发即弃,并立即reply,那么这是正确的代码。此外,我不会严格地说它是“忘记”,因为您仍然使用查询结果通过 websocket 发送它。你的代码很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-08
  • 2021-02-26
  • 2021-12-13
  • 2022-08-14
相关资源
最近更新 更多