Paul Grimshaw
Paul Grimshaw

Reputation: 21014

Javascript Promise Chain - ES6

I am trying to chain up some promises, but having trouble due to understanding the concepts.

I am trying to return some data from a database, only if the row count is less than a selected amount, otherwise it will return an error.

So far I have a method to fetch data and return a promise like so:

fetchDataPoints(dataset,fields,startTimestamp,endTimestamp){

        let self = this;
        let queryBody =  " FROM [bi].[" + dataset + "] " +
            "WHERE [timestamp]  >= '" + startTimestamp.format("YYYY-MM-DD HH:mm:ss") + "' "  +
            "AND   [timestamp]  <  '" + endTimestamp.format("YYYY-MM-DD HH:mm:ss") + "' " ;


        let rowCountCheck = new Promise(function(resolve,reject) {
            let request = new self.sql.Request();

            let rowCheckQueryString = "SELECT COUNT(*) AS row_count " + queryBody;
            request.query(rowCheckQueryString).then(function(recordSet){
                if (recordSet[0].row_count > self._rowLimit) {
                    reject("Too many rows");
                } else {
                    resolve();
                }
            });
        });

        let request = new self.sql.Request();

        let fieldsString = "[timestamp],[etl_timestamp]";
        for(let i = 0; i < fields.length; i++){
            fieldsString += ",[" + fields[i] + "]";
        }
        let  resultQueryString = "SELECT " + fieldsString + queryBody + " ORDER BY [timestamp] DESC";
        let resultQuery = request.query(resultQueryString);

        return rowCountCheck.then(resultQuery);

    }

However this is not working in the expected manner. Would someone who is more familiar with Promises be able to clarify how they'd be used for this kind of thing?

Upvotes: 0

Views: 99

Answers (1)

Dhananjaya Kuppu
Dhananjaya Kuppu

Reputation: 1322

You can return request.query, instead of using it as a call back function:

return rowCountCheck.then(function(response){
        let request = new self.sql.Request();
        let fieldsString = "[timestamp],[etl_timestamp]";

        for(let i = 0;i < fields.length; i++){
            fieldsString += ",[" + fields[i] + "]";
        }

        let  resultQueryString = "SELECT " + fieldsString + queryBody + " ORDER BY [timestamp] DESC";

        return request.query(resultQueryString);
});
`

Upvotes: 2

Related Questions