I am using the following code in Node.js to call a database query using a promise. That part works fine. I am attempting to 'pause' my script execution until the database query completes...that is the part causing a problem.
my code:
var _startup = 1; //toggle to check database on web server reboots...
var isPaused = 1; //toggle to 'delay' database call function...
const db = require('./routes/queries');
app.get('/lookup', function (req, res) {
if (_startup === 1) {
isPaused = 1;
_line_update(); //create/update member status arrays...
//'delay' until '_line_update()' has completed...
function waitForIt(){
if (isPaused === 1) {
setTimeout(function(){waitForIt()},100);
} else {
console.log("DATABASE CALL COMPLETED...");
console.log(lineup);
console.log(picture);
console.log(present);
};
}
_startup = 0; //toggle 'off'
}
});
function _line_update() {
lineup = [];
picture = [];
present = []; //create an 'empty' array EACH CALL...
//**Query PostGres database...using a promise
db.getMembers()
.then(function(value) {
console.log('Async success!', value);
console.log('length of value passed from database query: ' + value.length);
//...DO STUFF HERE TO POPULATE ARRAYS ('lineup', 'picture', 'present')
isPaused = 0;
console.log("isPaused at function call ending: " + isPaused);
})
.catch(function(err) {
console.log('Caught an error!', err);
});
}
Here the output in the console can be seen. The initial "Async success!" prints followed by the output of the object (as returned by the database call), as it should. In addition I see the 'isPaused' variable being changed to "0" when the 'resolved' (.then) statement finishes...as it should...however then everything seems to 'hang'...I do not see any log printouts for my "DATABASE CALL COMPLETED" and the associated arrays that should have populated at that point...
Async success! [ { name: 'administration',
pass: 'peace',
status: 'active',
login: '2090',
logout: 'na',
service: 'both',
lucky: 'na',
picture: null,
picturex: null,
city: null,
state: null,
legacy: 'na' } ]
length of value passed from database query: 1
isPaused at function call ending: 0
//HANGS HERE AT THIS POINT...???
How can my code be modified so as to properly wait for the database call to complete (i.e. '_line_update()' which in turn calls 'db.getMembers')...? Thank you in advance for any suggestions.