The database queries themselves are not the issue - they work fine.
The problem is, I need to execute all of them sequentially:
DELETE FROM myTable;
INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z);
SELECT * FROM myTable;
And I can't figure out how to do that in Node, no matter what I try. This question seems to be the most-trafficked solution, and it would have me do something like this (where client is from pg and should be returning promises):
// client is my database client, has already been initialized
// f is an object corresponding to my database
var res;
Promise.resolve()
.then(() => {
console.log("Deleting");
return client.query("DELETE FROM FileFormat");
})
.then(() => {
console.log("Inserting");
return client.query("INSERT INTO myTable(c1, c2, c3) VALUES ($1, $2, $3)", [f.x, f.y, f.z]);
})
.then(() => {
console.log("Selecting");
return client.query("SELECT * FROM FileFormat").then((err, result) => res = result.rows)
})
.then(() => {
console.log("Finished");
console.log(res);
})
I would expect it to print Deleting, then Inserting, then Selecting, then Finished, then the data I just inserted into the database.
Instead, it's printing Deleting and then doing nothing.
I don't want to chain client.query.then(client.query.then(...)) infinitely, because that makes my code grow arbitrarily far indented. I would rather keep my code as flat as possible, and execute these calls sequentially, waiting for each one to finish before starting the next. How do I do that?