簡體   English   中英

Node.js在.then鏈中重復數據庫請求

[英]Node.js repeat database request in .then chain

我用一個承諾.then鏈條。 在此鏈中,我計算了一些界限,構建了sql語句並將請求發送到數據庫。 如果數據庫請求沒有結果,我想通過計算邊界來更改某些內容,然后再次執行相同的步驟。 我要重復此操作,直到獲得數據庫結果為止。

這是我的代碼:

.then(function(){
    return calcBound.calcBounds(req.body,0);
  })
  .then(function(options){
    return sqlStatementBuilder.sqlStatementBuilder(options);
  })
  .then(function(statement){
    return db_request.db_request(statement);
  })
  .then(function(dbResult){
    if(dbResult.length <= 0){ // if there are no results from the database
      console.log("There are no results for this filter options");
      var newDBResult;
      do{
        newDBResult = calcBound.calcBounds(req.body, addToOffset)              
                .then(function(options){
                  return sqlStatementBuilder.sqlStatementBuilder(options);
                })
                .then(function(statement){
                  return db_request.db_request(statement);
                })
      } while(dbResult.length <= 0);
      return newDBResult.sort(sortArray.compareRecordId);
    }else{
      return dbResult.sort(sortArray.compareRecordId);
    }
  })

while循環不是一個好主意,這最終將導致“內存不足”。

有什么更好的解決方案呢?

使用addToOffset作為參數創建一個函數dummyRecursiveFunction並調用它,直到在dbResult獲得結果dbResult

function dummyRecursiveFunction(addToOffset) {
  someFunction()
  .then(function(){
    return calcBound.calcBounds(req.body, addToOffset);
  })
  .then(function(options){
    return sqlStatementBuilder.sqlStatementBuilder(options);
  })
  .then(function(statement){
    return db_request.db_request(statement);
  })
  .then(function(dbResult) {
    if(dbResult.length > 0) {
      return dbResult.sort(sortArray.compareRecordId);
    } else {
      // newOffset: Your recalculated offset value.
      dummyRecursiveFunction(newOffset);
    }
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM