Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't get an ES6 promise to work

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.

like image 462
erv Avatar asked Dec 08 '25 18:12

erv


1 Answers

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");
});
like image 160
Jaydip Jadhav Avatar answered Dec 10 '25 10:12

Jaydip Jadhav