2016-03-21 202 views
0

我試圖鏈接一些承諾,但由於瞭解概念有麻煩。Javascript承諾鏈 - ES6

我想從數據庫返回一些數據,只有當行數小於選定的數量,否則它會返回一個錯誤。

到目前爲止,我有像這樣獲取數據並返回一個承諾的方法:

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

    } 

然而,這在預期的方式是行不通的。對Promises更熟悉的人能夠澄清他們將如何用於這種事情嗎?

+0

避免['Promise'構造反模式](http://stackoverflow.com/q/23803743/1048572 )! 'request.query(...)'似乎已經返回一個承諾。 – Bergi

+0

您必須將回調函數而不是承諾傳遞給'then'的參數。 – Bergi

+0

request.query(...)確實會返回一個承諾,並且我想通過一個承諾。怎麼會這樣呢?我希望承諾在第一個查詢的行數過高時拒絕。 –

回答

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

運行良好。 –