Executing Statements in a Specific Order with Express and Sqlite3

I am having an issue creating a table and inserting an item into it using the node command. Despite my efforts to reorganize my script, the item is being inserted before the table is created. Interestingly, manually inputting the commands in sqlite3 works as expected. Is there a way to control the order of execution in my script?

index.js

const express = require("express");
const cors = require("cors");
const sqlite3 = require("sqlite3").verbose();
const app = express();

app.use(cors());

let db = new sqlite3.Database("./database.db", err => {
    try {
        console.log("Successful connection to the database");
    } catch {
        console.error(err.message);
    }
});

statements = ["CREATE TABLE IF NOT EXISTS Products (product TEXT, price INTEGER);", "INSERT INTO Products (product, price) VALUES ('Apple', 5.99);"]
statements.forEach(statement => db.run(statement, err => {
    try {
        console.log(statement + ": successful!");
    } catch {
        console.error(err.message);
    }
}));

app.listen(3000, () => {
    console.log("Connection: http://localhost:3000/")
})

Output:

Connection: http://localhost:3000/
Successful connection to the database
INSERT INTO Products (product, price) VALUES ('Apple', 5.99);: successful!
CREATE TABLE IF NOT EXISTS Products (product TEXT, price INTEGER);: successful!

Answer №1

One possible reason for the issue you're encountering is due to the asynchronous nature of the db.run function within your foreach statement. To address this, consider implementing the following solution:

const express = require("express");
const cors = require("cors");
const sqlite3 = require("sqlite3").verbose();
const app = express();

app.use(cors());
// Establish connection to the database
let db = new sqlite3.Database("./database.db", err => {
  if (err) { // Handle connection failure
    console.error(err.message);
  } else {
    console.log("Database connection successful");

    // Create table
    db.run("CREATE TABLE IF NOT EXISTS Products (product TEXT, price INTEGER);", err => {
      if (err) {
        console.error(err.message);
      } else {
        console.log("Table created successfully");

        // Insert data once table is created
        db.run("INSERT INTO Products (product, price) VALUES ('Apple', 5.99);", err => {
          if (err) {
            console.error(err.message);
          } else {
            console.log("Data inserted successfully");
          }
        });
      }
    });
  }
});
app.listen(3000, () => {
  console.log("Server running at: http://localhost:3000/")
});

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

Wrap each object in a container and then insert its key and values into that container using jQuery

How can I wrap each item and then insert the object's indexes and values into each created wrapper? I've attempted to accomplish this using the following code: $.ajax({ url: "some url", type: "GET", success: function(data) { var data ...

What could be causing me to see a basic checkbox instead of a toggle switch in my React application?

I've been attempting to create a toggle switch that activates dark mode using Bootstrap switches, but when I save the code, it reverts back to a basic checkbox. According to the documentation, for older assistive technologies, these switch elements wi ...

Interactive Form directly linked to SQLite3 database

Looking for assistance with converting a modal from static, fake data to dynamic data from an SQLite3 database. The goal is to display a table of existing data and allow users to add new rows by clicking a +New button. However, when trying to incorporate ...

After a period of activity, requests to Node.js with Express may become unresponsive

My server is running smoothly but after some time, it stops responding to requests. When I try to load the page, it gives me a "couldn't establish connection" error message. Here is my app.js: var express = require('express'); var path = r ...

Retrieving API Data in React Using the MERN Stack

Can anyone help me understand why I'm logging an empty array [] in my console even though I'm getting results from my API? This is my Node.js code: app.get("/todos", async (req, res) => { const todos = await todo.find() res.json(todos ...

Rendering Information in Angular 4 Through Rest API

Encountering issues displaying data from my local express.js REST API, organized as follows: people: [{ surname: 'testsurname', name: 'testname', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

Steps for displaying the output of a post request in printing

I am currently working on creating a basic search bar functionality for daycares based on user input. I am utilizing a post request to an API and receiving back a list of daycares that match the input. Below is the code snippet: <template> <div ...

Update the file name while utilizing express/multer

Having a bit of an issue with uploading a pdf file. When I try to upload it using ng-file-upload, the JSON data that gets sent to express.js looks like this: { fieldname: 'file', originalname: 'db.pdf', encoding: '7bit', ...

Need to create a callback within a sequence of events?

Is it possible to create a callback chain like this? Widget.update(...).onUpdate(function(data){ console.log('updated'); }); Here is the current code snippet: var Gateway = {}; Gateway.put = function(url, data, callback) { $.ajax({ ...

Is there a method to globally import "typings" in Visual Code without having to make changes to every JS file?

Is there a method to streamline the process of inputting reference paths for typings in Visual Studio Code without requiring manual typing? Perhaps by utilizing a configuration file that directs to all typings within the project, eliminating the need to ...

Content in the <core-animation-pages> element is extending beyond the borders of the main DIV when the "slide-from-right" effect is applied (Polymer

Check out this quick video I made to demonstrate the issue: I have successfully incorporated core-animation-pages into my web application. I have three different divs that transition using the slide-from-right animation without any problems. However, in d ...

How to delete the final character from a file stream using node.js and the fs module

My current project involves using node.js to create an array of objects and save them to a file, utilizing the fs library. Initially, I set up the write stream with var file = fs.createWriteStream('arrayOfObjects.json'); and wrote an opening brac ...

Managing numerical data in a CSV file using JavaScript and Google Visualization Table

A JavaScript snippet provided below will load a CSV file named numericalData.csv, which contains headers in the first row and numerical values starting from the second row. The data is then displayed using a Google Visualization Table. I am looking to con ...

Attempting to transfer a property from one page to another using the Link component in NextJS

Currently, I have a page containing six Link elements that are meant to redirect to the same destination but with different props based on which link is clicked. To pass props, this is how I've implemented it: <Link href={{ pathname: '/pro ...

Personalized 404 Error Page on Repl.it

Is it possible to create a custom 404-not found page for a website built on Repl.it? I understand that typically you would access the .htaccess file if hosting it yourself, but what is the process when using Repl.it? How can I design my own 404-not found p ...

Utilize context.isPointInPath(x, y) in HTML5 Canvas for intricate shapes that contain multiple paths

I am currently working on a project that involves drawing a complex shape composed of 6 thin lines and two thick lines. In my code, I have defined 8 paths to achieve this: context.save(); context.lineWidth=2; var TAB_ABSTAND=10; var T ...

What is the best way to outline the specifications for a component?

I am currently working on a TypeScript component. component @customElement("my-component") export class MyComponent extends LitElement { @property({type: String}) myProperty = "" render() { return html`<p>my-component& ...

Loop through object in React

I have what seems to be a beginner question with potentially many answers available. The object named Country.js is defined as follows: const Country = { albania: { 'countryNo': 70, 'name': { ...

The unexpected behavior in React's reconciliation process: What is causing the state to remain unchanged?

While exploring the React documentation, I came across an interesting example of resetting state: here To better understand it, I created different sandboxes to experiment with. However, I am struggling to reconcile what I observe in each of them. Each s ...