I use a promise .then
chain. In this chain I calculate some bounds, build the sql statement and send a request to the database. 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".
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
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);
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.