Why does Javascript not recognize my constructor? Code Answer

I am having an issue where the script is not recognizing the constructor in the class and assumes that I am calling all the other functions as the constructions.

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

When I run this portion 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()
    }
})

This is the error I getting:

It Keeps telling me that the function is not a constructor

Can anyone please help

Answer

“add” and “close” are methods of your “Articles” class. Don’t use the “new” keyword when you call those methods

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

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji