I am new to node.js and pg-promise coming from a synchronis programming background it requires a new thinking.
I would to start with a scenario of running database initialisation before the main program logic.
Following this example: https://github.com/vitaly-t/pg-promise/wiki/Learn-by-Example#simple-select
db.any("select * from users where active=$1", [true])
.then(function (data) {
// success;
})
.catch(function (error) {
// error;
});
Would my code read as either:
db.query("DELETE FROM records")
.then(function (data) {
// success;
console.log("This is where all my main logic goes");
})
.catch(function (error) {
// error;
});
Or would it read as:
db.query("DELETE FROM records")
.then(function (data) {
// success;
})
.catch(function (error) {
// error;
});
console.log("This is where all my main logic goes");
My understanding is that with the latter the message would be displayed before the records were deleted.
Update: After reading numerous articles on promises and callbacks I understand that pg-promise uses chaining being .then and .catch for both success and error scenarios. I also now believe I understand the pg-promise command should be placed within a function wrapper such as:
function initialiseDB() {
db.query("DELETE FROM records")
.then(function (data) {
// success;
})
.catch(function (error) {
// error;
});
}
Then from within my code I would call the function with a simple command which would run the function asynchronously:
initialiseDB();
I am however still unsure of how this concept of asychronous coding and promises fits into the overall structure of a program as surely almost everything in a program would need the initialisation to be completed first. Accordingly would the entire program not need to be placed in the ".then" section of the function? i.e the only code at the top level would effectively be the intialiseDB() function?
// Start of code here
var pgp = require('pg-promise')();
//Configure the database connection
var config = {
user: 'username', //env var: PGUSER
database: 'database', //env var: PGDATABASE
password: 'password', //env var: PGPASSWORD
};
var db = pgp(config);
function initialiseDB() {
db.query("DELETE FROM records")
.then(function (data) {
// This is where the main program logic goes after this line;
})
.catch(function (error) {
// error;
});
}
// Commence the program here
initialiseDB();