大多数文章都提到 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();
最佳答案
事实上,您不能在这里直接使用 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();
关于javascript - 使用 async/await 继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53924002/