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 = fileArray[i].location;
  imgLocationArray.push(fileLocation);
  knex("files")
    .insert({
      fileLink: fileLocation,
      todoId: todoId,
      userId: userId
    })
    .then(() => {
      console.log("First one has run!");
    })
    .catch(err => console.log(err));
}

knex("files")
  .where("files.userId", userId)
  .then(userFiles => {
    console.log("This one runs later");
    res.json({
      userFiles: userFiles
    });
  })
  .catch(err => console.log(err));

Answer №1

When working with promises (such as in Knex queries), Javascript will move on to the next statement without waiting for the previous one to complete. This is the issue you are facing: your code initiates all the database inserts, but does not wait for them to finish before executing the query to retrieve the data.

Since you are looping through a series of files, using Promise.all would be an effective solution. Here is how it operates. First, gather all the promises:

const insertions = fileArray.map(file => {
  fileLocation = fileArray[i].location;
  imgLocationArray.push(fileLocation);
  return knex("files")
    .insert({
      fileLink: fileLocation,
      todoId: todoId,
      userId: userId
    })
})

Take note of the return statement here, as it is crucial. Next, we must await the completion of all these promises:

Promise.all(insertions)
    .then(() => knex("files").where("files.userId", userId))
    .then(userFiles => {
      console.log("Error occurred");
      res.json({
        userFiles: userFiles
      });
    })
    .catch(err => console.log(err));

Only within this final .then block can we rely on the availability of the data to us, since all preceding queries have finished.

If you are fortunate enough to work in an environment on your server where async/await is supported (Node versions after 7.6), you can utilize the following approach:

try {
  await Promise.all(insertions);
  const userFiles = await knex("files").where("files.userId", userId);
  res.json({ userFiles });
} catch (e) {
  // Handle any database errors
}

Many individuals find this syntax more easily understandable. Remember that the function containing this code must be defined with the async keyword:

myExpressRouter.post("userfiles", async (req, res) => {
  // ...
})

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

Combining shared table rows with embedded ruby code in Javascript - is it possible?

I'm a new Javascript learner and I'm attempting to create a function that will merge rows with the same value (year in this case) and add their numbers together. Although my code isn't functioning as expected, it also doesn't seem to be ...

Error message appears when trying to render a shallow mock of a React.Component that extends MyInterface with any type

Encountering an Issue with Component Mocking When attempting to mock a component, I am receiving the following error message: "Conversion of type '{ props: { index: number; AssignmentTitle: string; AssignmentDescription: string; AssignmentUtilizedHou ...

A step-by-step guide on selecting a checkbox within an alert popup using Selenium with Java

Hello everyone, I am struggling to find a solution for checking and unchecking a checkbox located in an alert window or modal pop-ups. We have three types of pop-ups: alert, confirm, and prompt. Specifically, in the confirm popup, there is a checkbox t ...

Ways to have a function return a promise from the final "then" in a series of promises

I am delving into the world of test automation with Selenium and JavaScript. As a newcomer to both, along with functional programming and promises, I am facing a challenge in creating a function that performs three essential tasks: Click on an input Clea ...

Removing other objects with Mongoose after an update

I'm facing an issue with my update query in mongoose. I can't figure out why other objects are getting deleted when I only intend to update one specific object. The code is functioning correctly in terms of updating, but it's causing all the ...

Automatically copy any chosen selection on the page to the clipboard

Is there a way to copy any selection from a webpage to the clipboard, regardless of where it is located on the page (div, text input, password input, span, etc.)? I have created a function that can retrieve the selected text, but I am struggling with sett ...

Prevent the Rain from descending

Looking for a way to toggle a particle emitter on or off, I've encountered memory leaks with my Reactjs code that generates rain/snow particles using the canvas element. Despite attempts to stop the animation properly, it seems to be projecting a new ...

What is the significance of `cursor.exec` in MongoDB?

Searching tirelessly, yet the information remains elusive. var cursor = db.collection('students'); cursor.skip(10).limit(10) cursor.exec(function(err, result) {...}) Are there any docs available regarding the function of exec? ...

Retrieving items from an array based on their class association

My challenge involves handling a list of items obtained using the following code: var searchResultItems = $(resultContainerId + ' li'); Each item in the search results can have different classes. How can I extract all items with a specific clas ...

Start up a NodeJs Express application on the main URL using Nginx

Scenario I have a unique application built with PHP that is currently hosted on a domain called example.com. It runs on an nginx server. Recently, I developed a new NodeJS express application that needs to be deployed on example.com/nodeApp (without the t ...

What is the best way to eliminate a specific value within a flatmap?

This is the flatMap: const choices = names.flatMap( (item) => item.name + " - " + item.size + "- " + item.category ); console.log(choices): https://i.stack.imgur.com/MO4b1.png If the item.category is equal to S-XL, how can ...

Ways to fix the error message 'yarn package has unresolved peer dependency'

Whenever I run yarn upgrade or install, a bunch of warnings pop up due to unmet peerDependencies. warning " > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4322332c2f2f2c6e2f2a2d286e2b37373303726d766d7a">[email pro ...

Is it possible to define a variable within a JavaScript function and then access it outside of the function?

I have a Node.js application where I need to define a variable inside a function and access its value outside the function as well. Can someone provide guidance on how to achieve this in my code? var readline = require('readline'); var rl = read ...

Disable the mousedown event in JavaScript/jQuery

During a drag and drop operation, I have set certain limits on the screen. When the draggable object passes these limits, I want it to return to its original position. The issue I am facing is that if the onmousedown event is active, the object does not r ...

Issue with Bootstrap Navbar dropdown causing page refresh instead of menu dropdown activation

<!DOCTYPE html> <html lang="en" dir="ltr" style="style.css"> <!-- All icons were courtesy of FlatIcon : www.flaticon.com and FreePik : www.freepik.com --> <head> <meta charset="utf-8"&g ...

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...

Modeling with Sequelize and express-session

Struggling to make express sessions compatible with postgres. After hours of debugging, all issues have been resolved except one. Everything functions correctly except for the following: When I run this query in pgAdmin, my sessions work properly: CREATE ...

What is the best method to retrieve multiple values from a select dropdown and showcase them in an input field using ajax?

I am currently working on fetching multiple values from a database using AJAX and PHP. I have a select option which fetches values from the database, and when an option is selected, I want to display related data that matches the ID of the current option. ...

How to verify changes in session variable using PHP and AJAX

Hey there! I'm looking for a way to continually monitor changes in a session variable within PHP. Let's say the session variable "x" starts off with a value of "1" and then, after five seconds, it changes to "2". This session variable "x" is up ...

Why do I continue to receive the error message "Cannot POST"?

I've been struggling with setting up a basic HTML form and an Express server. No matter what I do, the routing just doesn't seem to work. Every time I try to post something, I keep getting a "Cannot Post" error message. What am I doing wrong? ...