Encountering an unhandled promise rejection issue with Knex's batchInsert function when attempting to insert arrays larger than 3 elements

I am currently working on an express app and utilizing Knex as the query string builder.

During batch insert operations with an array of 1000+ objects, I encountered an error when the array exceeded a certain length. The specific error message is provided below in this question.

In my testing, I observed that if the testFields array contains 3 or fewer objects, the data gets inserted into the database successfully. However, any number greater than 3 triggers the mentioned error. This leads me to suspect that the issue lies in the array's size.

To investigate further, I isolated the problem by hardcoding the data set to be inserted. The variable testFields, which serves as input for the batchInsert method, can be found at the end of this post.

The database in use is hosted on Azure, and my node version stands at v12.18.0.

Here are the pertinent details from my package.json:

{
  "name": "expressjs",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www",
    "dev": "nodemon ./bin/www"
  },
  ...
}

Below, you will find the code snippets representing my Express route and Knex query logic.

const isolateProblem = (res) => {
  // need to get connection string from vault
  return getKnexWithConString
    .then((knex) => {
      return knex
        .batchInsert("Tasks", testFields)
        .returning("pk_Tasks")
        .then((result) => {
          res.send("okay");
          return result;
        })
        .catch((err) => {
          res.send("not okay 1");
          console.log("err", err);
        });
    })
    .catch((err) => {
      res.send("not okay");
      console.log("err2:", err);
    });
};

router.get("/", async (req, res) => {
  const data = await isolateProblem(res);
  console.log("data", data);
});

The error I'm encountering occurs when the array surpasses 3 elements. It appears to be an unhandled promise warning originating from transaction.js:45:38, but I'm unsure about the root cause.

"(node:805) UnhandledPromiseRejectionWarning: TypeError: Cannot assign to read-only property 'originalError' of object 'TransactionError: Requests can only be made in the LoggedIn state, not the Final state' at ...node_modules/knex/lib/dialects/mssql/transaction.js:45:38 (node:805) UnhandledPromiseRejectionWarning: Unhandled promise rejection.

This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:805) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code."

The testFields array below illustrates the structure of the objects being processed. Note that for privacy reasons, sensitive field names and values have been obfuscated.

Given that this array has 4 elements, it triggers the aforementioned error. Removing one element from this array would allow the data insertion to proceed without issues.

Your assistance and insights on resolving this matter are greatly appreciated!

const testFields = [
  {
    SqlField1: "00000",
    ...
  },
  ...
]

Answer №1

Encountering the same issue, I conducted various tests to discover that the behavior is influenced by the number and possibly the size of the parameters utilized in batchinsert.

A data array a = [{"a":1,"b":"1"},...] with a size of 64 gets inserted without any issues. However, adding one element {"a":1,"b":"1"} results in an error.

It seems like having 128 parameters for the prepared statement might be the limit that ultimately leads to the failure?

  • "knex": "^0.20.11"
  • "mssql": "^5.1.1"
  • node v12.14.1

I'm left with the following options:

  • Divide my Data into chunks suitable for batchinsert processing :-(
  • Switch to singleton inserts directly :-((
  • Consider moving away from Knex / Nodejs and returning to Java,... :-(((

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

preclude any dates prior to the chosen date

I need a solution for a scenario where I have 5 datepickers in sequence. When I select a date on the first picker, all previous dates should be disabled when selecting on the next picker. Additionally, once a date is selected on one picker, the following ...

Enabling parameters in Express middleware disrupts the functionality of other routes

One issue I'm encountering is that when I implement a middleware on a path with parameters, the middleware ends up being applied to other routes that don't have those same parameters. Here's an example of my code: app.use('/group/:gro ...

Using Array.push on MongoDB does not appear to function as expected

My goal is to implement a dynamic vector/array feature in MongoDB where each submission made by a user will update the database accordingly. I have already created a variable for this purpose and tested it successfully with the correct user being found. H ...

Setting a consistent theme or style for all HTML/React tags using a selector inside a specific component

Here's a simplified example of what I'm trying to do: I'm using Material UI Styles for styling my components. I want to style all the <Link> tags in my component. For instance: const useStyles = makeStyles(theme => ({ menuLink: ...

Libraries that provide webkit support for all browsers

Looking for a library that supports CSS webkit across various browsers, including older ones like ie6. Preferably written in JavaScript. Any recommendations? ...

The identical page content is displayed on each and every URL

Implementing a multi-step form in Next JS involves adding specific code within the app.js file. Here is an example of how it can be done: import React from "react"; import ReactDOM from "react-dom"; // Other necessary imports... // Add ...

Implement a Selection Feature in Angular

Currently, I am working on an application where users can add new rows with the same fields. One of the requirements is to allow users to add an option to a select element. While I have successfully implemented this in jQuery, I am facing challenges integr ...

jQuery encountering error when uploading multiple files upon loading

I'm having trouble with this jQuery plugin ( ). Whenever I try to set the events on it, I keep getting an error message saying "Function expected". Can someone provide assistance? Everything seems to be working fine except for binding to the events. ...

Incorporating CASL with the latest version of Angular, version

I'm currently working on implementing CASL into my Angular application, but I'm having trouble understanding how to integrate it. // Login Component ngOnInit() { var jsonBody = {}; jsonBody['email'] = 'peter@klaven'; ...

What is the best way to increment the value of an input by any number using JavaScript and HTML?

My code is causing a NaN error, and I'm struggling to identify the root cause. Even providing a specific number in the addnum function did not resolve the issue. <script> var result = document.getElementById("result"); var inputVal = ...

Capture latitude and longitude using HTML5 Geolocation and store the values in a PHP variable

In the midst of a project, I am tasked with obtaining the longitude and latitude of a user in order to pinpoint their location. The challenge lies in storing this data in PHP variables, which will ultimately be saved in a MySQL database. Can anyone offer ...

What is the most effective way to utilize zoom with an Orthographic projection?

I'm attempting to utilize THREE.OrbitControls for zooming in an orthographic projection, but I'm not achieving the desired outcome. I believe it may be possible to adjust the viewSize that is multiplied by left, right, top, and bottom to achieve ...

React useEffect not working when using the default state

I'm currently facing an issue where setting the page to its default value from the refresh function does not trigger the useEffect hook on the first attempt. However, if I run the refresh function for the second time, it works fine. Interestingly, thi ...

Is my Magento journey on the correct course?

I am wanting to include or require a file in DATA.php within magento. Below is the code snippet I have: public function formatPrice($price) { require_once(Mage::getBaseDir('app').'\design\frontend\neighborhood ...

How is it that cross-domain scripting is able to occur with local files on a smartphone or tablet?

My Experiment: To test cross-site scripting (XSS), I set up an index.html file with a xss.js script that utilized the jQuery.get() function. After opening the index.html in various browsers (Firefox, Chrome, IE, and Opera), I attempted to trigger an ajax ...

Is it possible to use next.js to statically render dynamic pages without the data being available during the build process?

In the latest documentation for next.js, it states that dynamic routes can be managed by offering the route data to getStaticProps and getStaticPaths. Is there a way I can create dynamic routes without having to use getStaticProps() and getStaticPaths(), ...

I'm curious about something I noticed in an HTML example within the text content section of elements. Can you help clarify this for me?

I recently came across a repository that was part of a bootcamp curriculum for learning full stack development. In one of the lessons on jQuery, students were tasked with building a calculator. However, I noticed some strange variables in the HTML where te ...

Retrieving users by their Id's from MySql database using NodeJS

Goal: I aim to gather a list of users from a table based on the currently logged-in user. I have successfully stored all user IDs in an array and now wish to query those users to display a new list on the front end. Progress Made: I have imported necessa ...

Data retrieval takes precedence over data insertion

I'm facing an issue where I am trying to insert data into MySQL using Knex within a loop, but the data retrieval is happening before the insertion. Can anyone assist me with this problem? for (let i = 0; i < fileArray.length; i++) { fileLocation ...

How to Use a RawQuery to Retrieve All Data from an Android SQLite Database where the Column Matches the Username

I am currently working on a feature that links user input data directly back to them. This involves a login process that checks the username and password in SQLite, and if there is a match, it starts an activity intent and saves the details in SharedPref. ...