I am busy trying to use knex.js within custom modules.
knex will well documented and not prosing too much problem EXCEPT i have never worked with promises before, not really a .js programmer (yet, working hard on it as i never use a any of the others i learned over the years)
so as a simple example
const db = this.getDbConnection(connection);
if (!db) throw new Error(`Connection "${connection}" doesn't exist.`);
sqlCode="select username from users where userid = 1";
let results = await db.raw(sqlCode);
// raw method returns raw response from driver, needs some conversion (http://knexjs.org/#Raw-Queries)
if (db.client.config.client == 'mysql' || db.client.config.client == 'mysql2') {
results = results[0];
} else if (db.client.config.client == 'postgres' || db.client.config.client == 'redshift') {
results = results.row;
}
console.log(results); // correctly outputs the content of results
return results;
but the code returns an object as a promise
i can view the returned data with
console.log(results)
[ { username: 'Brian' } ]
using "typeof" datatype is shown as : Promise { 'object' }
What do i need to do to resolve the promise and then use the returned data in subsequent operations.
While the value can be obtained as above, that does not mean that the promise has been resolved so sometimes when trying to address the value, the data is not available and i see
value is: [object Promise]
this seems to follow any subsequent knex() call (the module i am writing makes data queries in a loop so they happen quickly)
Guessing i need some code to check that the promise has been returned.
Time to stop coding project for a while and start reading all about promises i guess.
I remember when I was first learning about Promises. Took me quite a fair amount of time to learn. In fact, I despised it so much I went straight for the experimental async/await. Only months later when I had to "promisify" a callback style function is that it clicked for me
By the way, a callback style function is older than promises.
The goal of async/await is you can write asynchronous code in a synchronous manner.
The next evolution is outside Javascript, it's in the Go programming language, it's wonderful for building async stuff.