Javascript Promise Chain - ES6

时间:2016-03-21 12:27:12

标签: javascript node.js ecmascript-6

我正在尝试将一些承诺捆绑起来,但由于理解这些概念而遇到麻烦。

我试图从数据库返回一些数据,只有当行数少于所选数量时才会返回,否则会返回错误。

到目前为止,我有一个方法来获取数据并返回一个这样的承诺:

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);

    }

然而,这不符合预期的方式。那些更熟悉Promise的人是否能够澄清他们如何被用于此类事情?

1 个答案:

答案 0 :(得分:2)

您可以返回request.query,而不是将其用作回调函数:

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);
});
`