I am new to promises. I apologize I did see that similar questions have been asked here before, but it is still unclear to me how to make it work. I am trying to access value that is supposedly gets returned by the promise inside my .then()
block. I need to be able access results of my SQL queries that I run inside the .then()
blocks for some data validation in my testing framework.
This version perfectly works and I get result of my SQL query in the console.
const mysqlssh = require('mysql-ssh');
const fs = require('fs');
let conn = mysqlssh.connect(
{
host: '***',
user: '***',
privateKey: fs.readFileSync( process.env.HOME + '***')
},
{
host: '***',
user: '***',
password: '***',
database: '***'
})
const query1 = 'SELECT count(*) as cnt FROM table';
conn.then(function(client) {
client.query(query1, function (err, result) {
console.log(result[0].cnt)
})
})
With this version my console logs promise in a pending state:
const mysqlssh = require('mysql-ssh');
const fs = require('fs');
let conn = mysqlssh.connect(
{
host: '***',
user: '***',
privateKey: fs.readFileSync( process.env.HOME + '***')
},
{
host: '***',
user: '***',
password: '***',
database: '***'
})
const query1 = 'SELECT count(*) as cnt FROM table';
let tableCount = conn.then(function(client) {
client.query(query1, function (err, result) {
return result[0].cnt
})
})
console.log(tableCount);
When I do console.log(result[0].cnt) inside my then
block - I perfectly see result in my console. However, if I try to assign it to a variable and then console log that variable I get Promise { <pending> }
message in the console.