如何在Node js中等待类构造器

时间:2019-10-22 04:40:03

标签: node.js async-await

我有两个班级,如下 AClient类

class AClient {
    constructor(AHeaderObj) {
        logger.info("inside tenant client constructor");
        this.tenant_uri = tenantHeaderObj.tenant_uri || config.TENANT_URI;
        this.refresh_token = tenantHeaderObj.refresh_token;
        this.tenant_header = tenantHeaderObj.tenant_header;
    }

BClient类

class BClient {
    constructor(b_client) {
        logger.info("Inside mongoClient/constructor ");
        this.tenant_client = tenant_client;
    }
async find(db_name, collection_name, selectorQuery) {
        try {
            logger.info("Inside mongoClient find records");
            let dbName = await getDB(db_name, this.tenant_client);
            let db = await getConnection(dbName, this.tenant_client);
            logger.info("selectorQuery"+JSON.stringify(selectorQuery));
            let doc = db.collection(collection_name).find(selectorQuery).toArray();
            logger.info("****************doc**********"+JSON.stringify(doc));
            return await promiseWrapper(null, doc);
        } catch (err) {
            logger.info("Caught error in mongoClient find records ", err);
            return await promiseWrapper(err, null);
        }
    }

    async findSome(db_name, collection_name, query, projection, sort, limit){
        logger.info("Inside mongoClient findSome records");
        try{
            let dbName = await gettDB(db_name, this.tenant_client);
            let db = await getConnection(dbName, this.tenant_client);
            var selector = [{ $match : query},
                { $project : projection},
                { $sort : sort}];
            if(limit > 0){
                selector.push({ $limit : limit})
            }
            let docs = db.collection(collection_name).aggregate(selector).toArray();
            return await promiseWrapper(null, docs);
        } catch (err) {
            logger.info("Caught error in mongoClient findSome records ", err);
            return await promiseWrapper(err, null);
        }
    }

现在我以以下两种方式使用它。一种方法起作用,另一种则不行。 情况1:不工作时

var searchAll = function (type, text, sortBy, sort, Code, AHeaderObj) {
    logger.info("Inside  searchAll  function.");
    var selector = mongoQuery.searchAll(type, text, sortBy, sort, Code);
    var AObj = new AClient(AHeaderObj);
    logger.info("123");
    var mongoObj = new BClient(AObj);
    logger.info("1235");

    var findSome = callbackify(mongoObj.findSome)
    logger.info("12356");

    return new Promise((resolve1, reject1) => {
        logger.info("123567");

        findSome(dBName, collectionName, selector.query, selector.projection, selector.sort, 999999999, function (err1, res1) {
            if (err1) {
                logger.error("Failed to find");
                reject1(err1);
            } else {
                logger.info("Successfully found");
                resolve1(res1)
            }
        });
    })
}

案例2:它在发挥魅力的地方。

var getId = function (id, headerObj, callback) {
    logger.info("inside getAccountById() START:");
    let selector = mongoQuery.GetAccByIdQueryWithIdModelVersion("Id", id, “version", "v2.1")
    let index = 0;
    var AObj = new AClient(AHeaderObj);
        logger.info("123");
        var mongoObj = new BClient(AObj);
        logger.info("1235");
    mongoObj.find(dBName, collectionName, selector).then((result) => {
        logger.info("123568");

        if (result && result.length > 0) {
            logger.info("a");
            logger.info("Found an with id: " + id);
            if (result[index].credentials.length > 0) {
            logger.info("getById() END:"+JSON.stringify(result));
            callback(null, result);
        }else {
            logger.info("b");
            let error = {
                "message": "Unable to fetch the with id: " + id

            };
            logger.warn(error.message);
            logger.info("getById() END:");
            callback(error, null);
        }
    }).catch((err) => {
        logger.info("c");
        logger.info("error" + JSON.stringify(err));
        callback(err, null);
    });
}

有人可以帮助我在Case1中做错什么吗?我观察到没有等待ion Case 1对象的创建,并且在出现错误的地方调用了db函数。

Caught error in mongoClient findSome records  TypeError: Cannot read property 'tenant_client' of undefined

1 个答案:

答案 0 :(得分:1)

不要试图等待类初始化,而应使构造函数为空,并提供与init异步的方法,该方法与构造函数的作用相同。

确保其他方法检查对象是否已通过init方法实例化,如果不是,则抛出错误:)