I am using Knex.js to insert values from an array into a PostgreSQL database. The problem I keep running into is that Knex will hang after inserting rows in the database.
I've been struggling with this for several hours, and have tried a variety of solutions, including Get Knex.js transactions working with ES7 async/await, Make KnexJS Transactions work with async/await, and Knex Transaction with Promises.
No matter which flavor I try, I come back to the hang. I'm pretty sure I'm missing something obvious, but it's possible I haven't had enough coffee.
Here's my test code:
const testArray = [
{line: 'Canterbury Tales'},
{line: 'Moby Dick'},
{line: 'Hamlet'}
];
const insertData = (dataArray) => {
return new Promise( (resolve, reject) => {
const data = dataArray.map(x => {
return {
file_line: x.line
};
});
let insertedRows;
db.insert(data)
.into('file_import')
.then((result) => {
insertedRows = result.rowCount;
resolve(insertedRows);
})
});
}
const testCall = (b) => {
insertData(b).then((result) => {
console.log(`${result} rows inserted.`);
})
}
testCall(testArray);
This returns the following:
3 rows inserted.
EDIT: Updating with solution
Thanks to @sigmus, I was able to get this working by adding db.destroy()
. Here's the updated code block, fully functional:
const testArray = [
{line: 'Canterbury Tales'},
{line: 'Moby Dick'},
{line: 'Hamlet'}
];
const insertData = (dataArray) => {
return new Promise( (resolve, reject) => {
const data = dataArray.map(x => {
return {
file_line: x.line
};
});
let insertedRows;
db.insert(data)
.into('file_import')
.then((result) => {
insertedRows = result.rowCount;
resolve(insertedRows);
})
.finally(() => {
db.destroy();
});
});
}
const testCall = (b) => {
insertData(b).then((result) => {
console.log(`${result} rows inserted.`);
process.exit(0);
})
}
testCall(testArray);