简体   繁体   English

Node.js在.then链中重复数据库请求

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

I use a promise .then chain. 我用一个承诺.then链条。 In this chain I calculate some bounds, build the sql statement and send a request to the database. 在此链中,我计算了一些界限,构建了sql语句并将请求发送到数据库。 If the database request gives no result, I want to change something by calculating the bounds and do the same steps again. 如果数据库请求没有结果,我想通过计算边界来更改某些内容,然后再次执行相同的步骤。 I want to repeat this until there is a database result. 我要重复此操作,直到获得数据库结果为止。

This is my code: 这是我的代码:

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

The while loop is not a good idea her this will end up as "heap out of memory". while循环不是一个好主意,这最终将导致“内存不足”。

What would be a better solution to do this? 有什么更好的解决方案呢?

Create a function dummyRecursiveFunction with addToOffset as a parameter and call it until you get results in dbResult 使用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