[英]Javascript: Async Function Chaining in Class with return this
I am trying to do function chaining in a Javascript class by returning this after each method, but somehow, it does not work..: 我试图通过在每个方法之后返回此方法来在Javascript类中进行函数链接,但是以某种方式,它不起作用..:
let sql = require('mssql');
let {logger} = require('../utils/logger');
let config = require('config');
//mssql_stellenanzeigen_config = config.get('stellenanzeigen');
mssql_doublettencheckui_config = config.get('doublettencheckui');
class MSSQLConnectionObject {
constructor(configuration) {
this.configuration = configuration;
this.connection = undefined;
this.requestObject = undefined;
}
async build() {
let pool;
try {
pool = await new sql.ConnectionPool(this.configuration).connect();
console.log("Connection established!: ", pool);
} catch(e) {
logger.error("No SQL Database config or wrong config. Can't establish connection to MSSQL Server. " + e);
}
this.requestObject = await new sql.Request(pool);
return this;
}
static async connect(config) {
let pool;
try {
pool = await new sql.ConnectionPool(config).connect();
console.log("Connection established!: ", pool);
} catch(e) {
logger.error("No SQL Database config or wrong config. Can't establish connection to MSSQL Server. " + e);
}
this.requestObject = await new sql.Request(pool);
return this;
}
async getBuchungsquelle() {
const query = `SELECT * FROM buchungsquelle`;
return await this.requestObject.query(query).then((result) => console.log(result)).catch(err => console.log(err));
}
}
module.exports = {
MSSQLConnectionObject
}
let query= `select * from buchungsquelle`;
let a = new MSSQLConnectionObject(mssql_doublettencheckui_config);
a.build().getBuchungsquelle();
I get an error: 我收到一个错误:
a.build().getBuchungsquelle();
TypeError: a.build(...).getBuchungsquelle is not a function
why does this not work? 为什么这不起作用? Is there an error in how to return this from my functions? 如何从我的函数中返回此错误?
It doesnt work because your function is Async
. 它不起作用,因为您的功能是Async
。
You are not actually returning a instance of MSSQLConnectionObject
but a instance of Promise<MSSQLConnectionObject>
. 您实际上不是在返回MSSQLConnectionObject
的实例,而是Promise<MSSQLConnectionObject>
的实例。
Check out this Stackoverflow post to get a nice example of async chaining! 查看此Stackoverflow帖子,以获取一个不错的异步链接示例!
TypeError: a.build(...).getBuchungsquelle is not a function TypeError:a.build(...)。getBuchungsquelle不是一个函数
build
is an async
function. build
是一个async
函数。 When you say return this
, it creates a function which returns a promise that resolves to this
, not a function that returns this
. 当您说return this
,它将创建一个函数,该函数返回一个可解决this
的promise ,而不是返回this
的函数。
So to use it you would need to wait for the promise to resolve and then call the next function in sequence. 因此,要使用它,您将需要等待promise解决, 然后依次调用下一个函数。
a.build().then( x => x.getBuchungsquelle() )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.