Javascript:类中的异步函数链接,返回此

时间:2019-05-21 09:43:21

标签: javascript function class method-chaining

我正在尝试通过在每个方法之后返回此方法来在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();

我收到一个错误:

a.build().getBuchungsquelle();            

TypeError: a.build(...).getBuchungsquelle is not a function

为什么这不起作用?如何从我的函数中返回此错误?

2 个答案:

答案 0 :(得分:2)

它不起作用,因为您的函数是Async

您实际上不是返回MSSQLConnectionObject的实例,而是返回Promise<MSSQLConnectionObject>的实例。

异步链接:

Check out this Stackoverflow post获得异步链接的一个很好的例子!

答案 1 :(得分:2)

  

TypeError:a.build(...)。getBuchungsquelle不是函数

buildasync函数。当您说return this时,它会创建一个函数,该函数返回一个可解析为this 的承诺,而不是一个返回this的函数。

因此,要使用它,您将需要等待promise的解决,然后然后依次调用下一个函数。

a.build().then( x => x.getBuchungsquelle() )