What could be causing JavaScript to fail in recognizing my constructor?

I encountered a problem where the script fails to recognize the constructor in the class and incorrectly assumes that I am calling all the other functions as constructors.

class Articles {
    constructor(dbName = ':memory:') {
        return(async() => {
            this.db = await sqlite.open(dbName)
            const sql =  //an Sql command goes here
            await this.db.run(sql)
            return this
        })()
    }
    async all() {
        const sql = 'SELECT users.user, articles.* FROM articles, users\
                        WHERE articles.userid = users.id;'
        const articles = await this.db.all(sql)
        for(const index in articles){
            if(articles[index].photo === null) articles[index].photo = 'avatar.jpg'
            const dateTime = new Date (articles[index].D&T)
            const date = `${dateTime.getDate()}/${dateTime.getMonth()+1}/${dateTime.getFullYear()}`
            articles[index].Date_Time = date
        }
        return articles
    }
    async add(data) {
        console.log('ADD')
        console.log(data)
        return true
    }
    async close() {
        await this.db.close()
    }
}
export default Articles

Upon executing this section of the code:

router.post('/add', async ctx => {
    const a = await new Articles(dbName)
    try{
        await new a.add(ctx.request.body)
        return ctx.redirect('/?msg=new article added')
    } catch(err) {
        console.log(err)
        await ctx.render('error', ctx.hbs)
    } finally {
        new a.close()
    }
})

The error message I receive states:

It Keeps telling me that the function is not a constructor

If you have any insights or solutions, please help. Thank you.

Answer №1

The methods "add" and "close" belong to the "Articles" class. Remember to not use the "new" keyword when calling these methods.

router.post('/add', async ctx => {
    const a = await new Articles(dbName)
    try{
        await a.add(ctx.request.body)    // <- Avoid using "new" keyword here
        return ctx.redirect('/?msg=new article added')
    } catch(err) {
        console.log(err)
        await ctx.render('error', ctx.hbs)
    } finally {
        a.close()    // <- Avoid using "new" keyword here
    }
})

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

Rendering with Next.js script

Within my Next.js project, there is a script implemented to render a widget. The code for this script looks like: <a className="e-widget no-button xdga generic-loader" href="https://example" rel="no ...

How can I efficiently make multiple API calls using redux-thunk?

This is the approach I took. const redux = require('redux') const thunkMiddleware = require('redux-thunk').default const axios = require('axios') const reduxLogger = require('redux-logger') const createStore = redu ...

Understanding the functionality of app.locals within app.get in an Express application and how to effectively parse data

I am currently developing a parse application using express. In my index file, I want to display different information to users based on whether they are logged in or not. However, I am facing an issue with storing the flag and logged-in user name using ap ...

Getting an unexpected empty response when submitting a request with a combination of image files and json parameters through postman, nodejs, and express

For my university project, I am developing a RESTful API for an online ticket shop that works across multiple platforms. I am using nodejs and express to create this API. First, I created the model for each event: const mongoose = require('mongoose&ap ...

Leveraging AJAX and PHP for generating PDF files

My web application is designed to function in a specific way - the user fills out a form, and then using AJAX, the form data is sent to a PHP file that utilizes xpdf to generate a PDF. The goal is for the generated PDF to be easily downloadable on the HTML ...

Establishing header cache control within the KOA framework

I'm currently working on an app that is using the KOA framework, and I am struggling to understand why a specific page is being cached. Even after attempting a hard reload in all browsers, the changes do not appear unless the cache is cleared. I woul ...

Update in slide height to make slider responsive

My project involves a list with text and images for each item: <div class="slider"> <ul> <li> <div class="txt"><p>First slogan</p></div> <div class="img"><img src="http://placehold.it/80 ...

Navigating through JSON data that has been returned

When I use AJAX (jQuery) to query my database, the data I receive back is causing some difficulties. While searching for a solution, I came across similar issues posted by others who pointed out that the PHP code (specifically how data is stored in the arr ...

Tips for retrieving input values when they are not available in HTML documents

In this code snippet, I am creating an input element with the file type without adding it to the DOM. My goal is to retrieve the value of this input once the user selects a file. Even though the input is not part of the HTML template, I still want to acces ...

Finding the name of a particular item in an array and increasing its value - a step-by-step guide

For a homework project, I am developing a straightforward cart system. Could someone advise me on the best approach to retrieve an item from an array and increment its value by one? The array contains 25 items, each with a unique name but without any IDs a ...

Issues with Bootstrap-slider.js functionality

I'm having trouble getting the bootstrap-slider.js library from to function correctly. All I see are textboxes instead of the slider components. You can view an example at I have verified that the CSS and JS files are pointing to the correct direc ...

Exploring the depths of nested object arrays and navigating through historical indexes

I am working with nested object arrays within an array and looking to determine the path of a specific key. For instance: const dataList = [ [ [{id: 100,name: 'Test1'}, {id: 120,'Test12'}], [{id: 101,name: 'Test1&apo ...

Troubleshooting issue: Looping through array in Node.js with Express, JSON, and Handlebars not functioning correctly with

I'm struggling to grasp the concept of looping through an object in Handlebars and transferring information from one location to another. Here is a sample json file that I am attempting to read from. The file, named "testdata.json", contains: { &qu ...

Transfer the parameter from ajax function to the aspx.cs file

I've written some code using HTML, JS, and AJAX, but it's not functioning as expected. <script type="text/javascript"> function DeleteSelectedRecord(id) { alert(id); $.ajax({ type: "POST", ...

Most effective method for structuring a JSON format that contains recurring keys for every item within its array

Currently, I'm creating a JSON object that includes multiple addresses. My main concern is the potential for the JSON size to grow too large, which could impact browser performance and parsing speed in JavaScript. Each address includes keys such as "I ...

Ways to resolve the responseJSON showing {error: "invalid_request", error_description: "Code parameter is missing"}

My current issue involves uploading files to Google Drive from my Vuejs and JavaScript web application. The request I send is returning an error. Upon checking, I noticed that the variable code is null, and even the variable window.location.search is empty ...

Access a PHP file using XMLHttpRequest to run additional JavaScript code

My main page, referred to as Main.php, contains a button that triggers the display of results from Results.php within a div (divResults) on Main.php. The HTML content "These Are The Results" returned by Results.php is successfully displayed in the divResu ...

Navigation Bar Dropdown Menu Not Responding to Clicks

I'm having trouble implementing a dropdown menu in my navigation bar that should appear when the user clicks and disappear when they click anywhere outside of it, similar to Facebook's dropdown menu with options like logout. However, for some rea ...

Sorting of dates in mui-datatables is not accurate

I have dates that are formatted using moment.js, for example ("Sat, Feb 22, 2020 12:55 PM") I retrieve them from firestore, and they appear to come in correctly as I first sort them in descending order. forms.sort(function(left, right) { return moment.u ...

Receive notifications when there are modifications in the JSON data using AJAX and jQuery

Below is the code snippet I created: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Sample JSON Data Update</title> </head> <body> <style> span { font ...