0

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?

Paul Grimshaw
  • 19,894
  • 6
  • 40
  • 59
  • Avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572)! `request.query(…)` appears to already return a promise. – Bergi Mar 21 '16 at 12:30
  • You must pass a callback function, not a promise, as the argument to `then`. – Bergi Mar 21 '16 at 12:30
  • request.query(...) does return a promise, and I'd like to pass a promise back. How would one go about this? I would like the promise to reject when the row count from the first query is too high. – Paul Grimshaw Mar 21 '16 at 12:37

1 Answers1

2

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);
});
`
Dhananjaya Kuppu
  • 1,322
  • 9
  • 10