Transactions with node pg and foreach loop and async await
I am trying to insert multiple rows in PostgreSQL using node pg. I am using transactions but my query is executing after a response. I tried async await with my function but it is not working
This is my function
addPersons = async (req, res) => {
try {
await db.query("BEGIN");
req.body.forEach((person, index) => {
if (person.id) {
try {
await db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res
.status(Error_code.IdNotFound.code)
.send(Error_code.IdNotFound);
}
const query = `update person set
name = ${person.name},
where id = '${
person.id
}'`;
try {
await db.query(query);
} catch (error) {
try {
await db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res.status(500).send(err);
}
})
await db.query("COMMIT");
res.status(Error_code.Successfull.code).send(Error_code.Successfull);
} catch (error) {
try {
db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res
.status(Error_code.UnableToBeginTransaction.code)
.send(Error_code.UnableToBeginTransaction);
}
}
I also tried calling this function from another function and using foreach on that function but when whenever code detects await or callback in the second function it does not wait and return to the first function.
How can I run this code to add my data into PostgreSQL with transactions
Thanks
node.js postgresql node-postgres
add a comment |
I am trying to insert multiple rows in PostgreSQL using node pg. I am using transactions but my query is executing after a response. I tried async await with my function but it is not working
This is my function
addPersons = async (req, res) => {
try {
await db.query("BEGIN");
req.body.forEach((person, index) => {
if (person.id) {
try {
await db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res
.status(Error_code.IdNotFound.code)
.send(Error_code.IdNotFound);
}
const query = `update person set
name = ${person.name},
where id = '${
person.id
}'`;
try {
await db.query(query);
} catch (error) {
try {
await db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res.status(500).send(err);
}
})
await db.query("COMMIT");
res.status(Error_code.Successfull.code).send(Error_code.Successfull);
} catch (error) {
try {
db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res
.status(Error_code.UnableToBeginTransaction.code)
.send(Error_code.UnableToBeginTransaction);
}
}
I also tried calling this function from another function and using foreach on that function but when whenever code detects await or callback in the second function it does not wait and return to the first function.
How can I run this code to add my data into PostgreSQL with transactions
Thanks
node.js postgresql node-postgres
res.send
should be afterforEach
. Why don't you split your code into promises ?
– darklightcode
Nov 19 '18 at 7:08
1
Possible duplicate of Using async/await with a forEach loop
– estus
Nov 19 '18 at 7:10
@darklightcode res.status is after foreach. I didn't used promise in my code till now. I have 2 scenarios where I need to handle this situation that's why I am trying to avoid promises
– Unknown
Nov 19 '18 at 8:24
add a comment |
I am trying to insert multiple rows in PostgreSQL using node pg. I am using transactions but my query is executing after a response. I tried async await with my function but it is not working
This is my function
addPersons = async (req, res) => {
try {
await db.query("BEGIN");
req.body.forEach((person, index) => {
if (person.id) {
try {
await db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res
.status(Error_code.IdNotFound.code)
.send(Error_code.IdNotFound);
}
const query = `update person set
name = ${person.name},
where id = '${
person.id
}'`;
try {
await db.query(query);
} catch (error) {
try {
await db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res.status(500).send(err);
}
})
await db.query("COMMIT");
res.status(Error_code.Successfull.code).send(Error_code.Successfull);
} catch (error) {
try {
db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res
.status(Error_code.UnableToBeginTransaction.code)
.send(Error_code.UnableToBeginTransaction);
}
}
I also tried calling this function from another function and using foreach on that function but when whenever code detects await or callback in the second function it does not wait and return to the first function.
How can I run this code to add my data into PostgreSQL with transactions
Thanks
node.js postgresql node-postgres
I am trying to insert multiple rows in PostgreSQL using node pg. I am using transactions but my query is executing after a response. I tried async await with my function but it is not working
This is my function
addPersons = async (req, res) => {
try {
await db.query("BEGIN");
req.body.forEach((person, index) => {
if (person.id) {
try {
await db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res
.status(Error_code.IdNotFound.code)
.send(Error_code.IdNotFound);
}
const query = `update person set
name = ${person.name},
where id = '${
person.id
}'`;
try {
await db.query(query);
} catch (error) {
try {
await db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res.status(500).send(err);
}
})
await db.query("COMMIT");
res.status(Error_code.Successfull.code).send(Error_code.Successfull);
} catch (error) {
try {
db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res
.status(Error_code.UnableToBeginTransaction.code)
.send(Error_code.UnableToBeginTransaction);
}
}
I also tried calling this function from another function and using foreach on that function but when whenever code detects await or callback in the second function it does not wait and return to the first function.
How can I run this code to add my data into PostgreSQL with transactions
Thanks
node.js postgresql node-postgres
node.js postgresql node-postgres
edited Nov 19 '18 at 8:01
Sayed Mohd Ali
8861318
8861318
asked Nov 19 '18 at 6:30
UnknownUnknown
328
328
res.send
should be afterforEach
. Why don't you split your code into promises ?
– darklightcode
Nov 19 '18 at 7:08
1
Possible duplicate of Using async/await with a forEach loop
– estus
Nov 19 '18 at 7:10
@darklightcode res.status is after foreach. I didn't used promise in my code till now. I have 2 scenarios where I need to handle this situation that's why I am trying to avoid promises
– Unknown
Nov 19 '18 at 8:24
add a comment |
res.send
should be afterforEach
. Why don't you split your code into promises ?
– darklightcode
Nov 19 '18 at 7:08
1
Possible duplicate of Using async/await with a forEach loop
– estus
Nov 19 '18 at 7:10
@darklightcode res.status is after foreach. I didn't used promise in my code till now. I have 2 scenarios where I need to handle this situation that's why I am trying to avoid promises
– Unknown
Nov 19 '18 at 8:24
res.send
should be after forEach
. Why don't you split your code into promises ?– darklightcode
Nov 19 '18 at 7:08
res.send
should be after forEach
. Why don't you split your code into promises ?– darklightcode
Nov 19 '18 at 7:08
1
1
Possible duplicate of Using async/await with a forEach loop
– estus
Nov 19 '18 at 7:10
Possible duplicate of Using async/await with a forEach loop
– estus
Nov 19 '18 at 7:10
@darklightcode res.status is after foreach. I didn't used promise in my code till now. I have 2 scenarios where I need to handle this situation that's why I am trying to avoid promises
– Unknown
Nov 19 '18 at 8:24
@darklightcode res.status is after foreach. I didn't used promise in my code till now. I have 2 scenarios where I need to handle this situation that's why I am trying to avoid promises
– Unknown
Nov 19 '18 at 8:24
add a comment |
1 Answer
1
active
oldest
votes
Since this is tagged node-postgres
, I suggest that you base your code on the A pooled client with async/await example in the node-postgres documentation. I also suggest that you use parameterized queries or a query builder such as mongo-sql. (There are many, but that one's my favourite. 🙂)
It could look something like this:
const { Pool } = require("pg");
const pool = new Pool();
const addPersons = async (req, res) => {
const db = await pool.connect();
try {
await db.query("BEGIN");
const query = `update person set name = $1 where id = $2;`;
// Promise.all() may improve performance here, but I'm not sure if it's safe
// or even useful in the case of transactions.
for (const person of req.body) {
await db.query(query, [person.name, person.id]);
}
await db.query("COMMIT");
} catch (e) {
await db.query("ROLLBACK");
throw e;
} finally {
db.release();
}
};
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53369391%2ftransactions-with-node-pg-and-foreach-loop-and-async-await%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Since this is tagged node-postgres
, I suggest that you base your code on the A pooled client with async/await example in the node-postgres documentation. I also suggest that you use parameterized queries or a query builder such as mongo-sql. (There are many, but that one's my favourite. 🙂)
It could look something like this:
const { Pool } = require("pg");
const pool = new Pool();
const addPersons = async (req, res) => {
const db = await pool.connect();
try {
await db.query("BEGIN");
const query = `update person set name = $1 where id = $2;`;
// Promise.all() may improve performance here, but I'm not sure if it's safe
// or even useful in the case of transactions.
for (const person of req.body) {
await db.query(query, [person.name, person.id]);
}
await db.query("COMMIT");
} catch (e) {
await db.query("ROLLBACK");
throw e;
} finally {
db.release();
}
};
add a comment |
Since this is tagged node-postgres
, I suggest that you base your code on the A pooled client with async/await example in the node-postgres documentation. I also suggest that you use parameterized queries or a query builder such as mongo-sql. (There are many, but that one's my favourite. 🙂)
It could look something like this:
const { Pool } = require("pg");
const pool = new Pool();
const addPersons = async (req, res) => {
const db = await pool.connect();
try {
await db.query("BEGIN");
const query = `update person set name = $1 where id = $2;`;
// Promise.all() may improve performance here, but I'm not sure if it's safe
// or even useful in the case of transactions.
for (const person of req.body) {
await db.query(query, [person.name, person.id]);
}
await db.query("COMMIT");
} catch (e) {
await db.query("ROLLBACK");
throw e;
} finally {
db.release();
}
};
add a comment |
Since this is tagged node-postgres
, I suggest that you base your code on the A pooled client with async/await example in the node-postgres documentation. I also suggest that you use parameterized queries or a query builder such as mongo-sql. (There are many, but that one's my favourite. 🙂)
It could look something like this:
const { Pool } = require("pg");
const pool = new Pool();
const addPersons = async (req, res) => {
const db = await pool.connect();
try {
await db.query("BEGIN");
const query = `update person set name = $1 where id = $2;`;
// Promise.all() may improve performance here, but I'm not sure if it's safe
// or even useful in the case of transactions.
for (const person of req.body) {
await db.query(query, [person.name, person.id]);
}
await db.query("COMMIT");
} catch (e) {
await db.query("ROLLBACK");
throw e;
} finally {
db.release();
}
};
Since this is tagged node-postgres
, I suggest that you base your code on the A pooled client with async/await example in the node-postgres documentation. I also suggest that you use parameterized queries or a query builder such as mongo-sql. (There are many, but that one's my favourite. 🙂)
It could look something like this:
const { Pool } = require("pg");
const pool = new Pool();
const addPersons = async (req, res) => {
const db = await pool.connect();
try {
await db.query("BEGIN");
const query = `update person set name = $1 where id = $2;`;
// Promise.all() may improve performance here, but I'm not sure if it's safe
// or even useful in the case of transactions.
for (const person of req.body) {
await db.query(query, [person.name, person.id]);
}
await db.query("COMMIT");
} catch (e) {
await db.query("ROLLBACK");
throw e;
} finally {
db.release();
}
};
answered Nov 28 '18 at 9:49
Carl von BlixenCarl von Blixen
18917
18917
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53369391%2ftransactions-with-node-pg-and-foreach-loop-and-async-await%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
res.send
should be afterforEach
. Why don't you split your code into promises ?– darklightcode
Nov 19 '18 at 7:08
1
Possible duplicate of Using async/await with a forEach loop
– estus
Nov 19 '18 at 7:10
@darklightcode res.status is after foreach. I didn't used promise in my code till now. I have 2 scenarios where I need to handle this situation that's why I am trying to avoid promises
– Unknown
Nov 19 '18 at 8:24