I can't grasp how promises work. So I figured I'd just jump in and try and create one to see if that helps. But the following returns an undefined value (arrTables):
app.get("/getTables", function (req, res) {
var arrTables = getTables().then(function(response) {
console.log("getTables() resolved");
console.log(arrTables.length);
console.log(arrTables[1].ID());
}, function(error) {
console.error("getTables() finished with an error");
});
});
function getTables() {
return new Promise(function(resolve, reject) {
while (mLobby.tlbCount() < LOBBY_SIZE) {
var objTable = new Table();
mLobby.addTable(objTable);
}
resolve(mLobby.tables);
});
}
new Table() references a custom class that makes an async database call. I'm trying to use promises to make sure that call resolves before I continue in the code. Can anyone point out where I've gone wrong?
Here's the console output:
getTables() resolved
undefined
(node:6580) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id:
1): TypeError: Cannot read property 'ID' of undefined
Edit to add: mLobby.tblCount starts out as 0, so it does enter the while loop.
The problem with the array variable. the GetTable method returns nothing and output of this method is stored in response variable not in arrTables variable. try to use response variable instead of arrTables
getTables().then(function(response) {
var arrTables = response //Added
console.log("getTables() resolved");
console.log(arrTables.length);
console.log(arrTables[1].ID);
}, function(error) {
console.error("getTables() finished with an error");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With