Wednesday 31 May 2017

How can I get the result of a promise in node & jade

I'm new to NodeJS and Jade/PUG so I know this can be a really simple question for many of you but for me I can't understeand any of the answers a get from the internet because the term 'Promise' and how it works is a little "confusing" for me. I am querying a postgre database to get several values from a table (really simple query). If I do this without using a promise everything works fine, console prints the result and everyone is happy, but when I try to store this result into a variable and pass it as a parameter to a Jade template things change.

I have read that, in order to do that, I need to use promises because it is more likely that when the variable is being accessed, the value might not be resolved yet and that's what Promises are for. So here I have my code:

hero.js:

getHeroes: function()
{
    //Initialize array
    var elem = [];
    console.log('Querying heroes');
    return new Promise((resolve, reject) =>
    {

        pg.connect(conString, function (err, client, done) 
        {
            if (err) 
            {
                return console.error('error fetching client from pool', err)
            }
            //Execute SELECT query
            client.query('SELECT name from heroe;', function (err, rows, result) 
            {
                //Iterate over results
                for (var i = 0; i < rows.rowCount; i++) 
                {
                    //PUSH result into arrays
                    elem.push(rows.rows[i].name);
                }
                done()
                if (err) 
                {
                    return console.error('error happened during query', err)
                }
                resolve(elem)
            })
        });

    })

}

And this the part of my server.js where I call that function:

app.get('/jade', (request, response) => {
var heroList = [];
heroList = hero.getHeroes();
console.log(heroList);
response.render('test_jade', {param1: 'test'});
})

that console.log shows up "Promise { pending }" and I don't know how to "listen to the resolved event and retrieve the value from it once it has finished".

Would appreciate any advice/solution or even a good Node.js manual where all this mess is explained for total newbies like me.

Thanks in advance!



via Ejher

No comments:

Post a Comment