【发布时间】:2019-08-30 19:33:19
【问题描述】:
所有使用 mssql 客户端包/繁琐驱动程序的示例都是针对异步/回调/承诺的,但我只是在开发一个使用有限的微服务,而且我对异步函数的理解仍然有点模糊。 这是我尝试使用 async/await 的原因:
报告生成类:
const mssql = require('mssql');
const events = require('events');
class reporter {
constructor(searcher, logger) {
// Pass in search type and value or log the error of none defined
this.lg = logger
if (searcher.type && searcher.content) {
this.lg.lg("reporter created", 3)
this.srchType = searcher.type;
this.srchContent = searcher.content;
} else {
this.lg.lg("!MISSING SEARCH PARAMETERS", 0);
this.err = "!MISSING SEARCH PARAMETERS";
}
}
proc() {
//DB Connect async
async () => {
try {
await mssql.connect('mssql://username:password@localhost/database')
this.result = await mssql.query`select * from mytable where id = ${this.searcher}`
} catch (err) {
// ... error checks
}
}
return this.result;
}
}
然后调用:
//Pass to reporter for resolution
var report1 = new reporter(searcher, logs);
report1.proc();
我确信这可能是实现这一目标的一种非常糟糕的方式,所以我也愿意接受任何关于实现最终目标的好方法的意见,但我仍然想知道是否可以同步完成.
【问题讨论】:
-
你可能不喜欢它,但 JavaScript 作为一种语言是为异步任务而设计的。您可能应该使用它。使用
await模拟同步行为; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript node.js database microservices node-modules