New to async and struggling. As an example below I wish to init a table then process it's contents by: a) Remove old data b) Insert a new record c) Read the table into an array d) Display the array
'use strict';
// ================================================================================
// Module dependencies
var pgp = require('pg-promise')();
// ================================================================================
//Configure the database connection
var config = {
user: 'user', //env var: PGUSER
database: 'database', //env var: PGDATABASE
password: 'password', //env var: PGPASSWORD
};
var db = pgp(config);
// ================================================================================
// Initialise rhe variables
var customers = [];
// ================================================================================
// Initialise table
db.none("DELETE FROM testing")
.then(function(data) {
console.log("Deleted old records");
// success;
})
.catch(function(error) {
console.log(error);
});
db.none("INSERT INTO testing (firstname, surname) VALUES ('Bob', 'Brown')")
.then(function(data) {
console.log("Inserted new record");
// success;
})
.catch(function(error) {
console.log(error);
});
// ================================================================================
// Display records
db.any("SELECT * FROM testing")
.then(function(data) {
console.log("Looping records");
data.forEach(function(row, index, data) {
customers.push(row.firstname, row.lastname);
console.log(row);
});
})
.catch(function(error) {
console.log(error);
});
console.log("The customers are:");
console.log(customers);
The output is not as desired but somewhat as expected. Interestingly after "Inserted new records" there is a 30 second wait before the command prompt is retuned.
The customers are:
[]
Looping records
anonymous {
id: 3,
firstname: 'Bob',
surname: 'Brown',
created: 2016-08-03T01:43:34.880Z }
Deleted old records
Inserted new record
My question is ultimately with async programming surely there are scenarios where actions need to be performed in sequence such as the example above and in such a scenario how can this be coded in an async environment such as node.js.