[英]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.