DEV Community

Varun Hegde
Varun Hegde

Posted on

How do i convert the following code to transaction in Node.js?

I have written this async function which calls bunch of async functions inside which executes INSERT or SELECT statements and each function needs the output from the previous one. There's a lot of of INSERT operation so its taking lot of time.

code --
async writeDataseq(bno, pno, textArr) {
const pageNoTablePacket = await this.writeToPageNoTable(bno, pno);
try {
let pgId = pageNoTablePacket.insertId;
if (pgId == 0) {
pgId = await this.getPgId(bno, pno);
}

for (let index = 0; index < textArr.length; index++) {
let leftWord = null;
let rightWord = null;
let word = textArr[index];
if (index - 1 >= 0) {
leftWord = textArr[index - 1];
}
if (index + 1 < textArr.length) {
rightWord = textArr[index + 1];
}
const wordPacket = await this.writeWordToDb(word);
let wordId = wordPacket.insertId;
if (wordId == 0) {
wordId = await this.getWordId(word);
}
const wordInstPacket = await this.writeWordInst(wordId, pgId);
const wordContextPacket = await this.writeWordContext(
wordInstId,
leftWord,
rightWord
);
}
//every operation finished
return 'everything done successfully';
} catch (error) {
throw Error(error);
}
}

I am using Mysql database and am using node-mysql driver. I want to commit everything at once in the end to make it fast. How can I achieve this ?

Thanks in advance.

Top comments (0)