Home > database >  How to call constructor function from within itself?
How to call constructor function from within itself?

Time:09-13

Good day,

I want a function to check if there are any files inside a folder, if there is no folder, make the folder and then run itself (function) again.

const fs = require('fs');
const writeFileAtomic = require('write-file-atomic');

class DataHandler {
    constructor() {
    }
}

DataHandler.prototype.checkDB = function() {
    return new Promise((resolve, reject) => {
        fs.readdir('./database', function (err, files) {
            if (err) {
                if (err.code = 'ENOENT') {
                    fs.mkdir('./database', () => {
                        return this.checkDB;
                    })
                } else {
                    reject();
                }
            }
            if (files) {
                console.log(files)
            }
        })
    })
}

module.exports = DataHandler;

I get errors using this, saying this.checkDB is not a function

CodePudding user response:

The fix maybe is to save this in a variable:

DataHandler.prototype.checkDB = function() {
    var dataHandler = this;
    return new Promise((resolve, reject) => {
        fs.readdir('./database', function (err, files) {
            if (err) {
                if (err.code = 'ENOENT') {
                    fs.mkdir('./database', () => {
                        return dataHandler.checkDB;
                    })
                } else {
                    reject();
                }
            }
            if (files) {
                console.log(files)
            }
        })
    })
}

A VERY basic explanation:

In javascript, when you put this inside of a function(){} it gets assigned to that function's object. Then, when you called fs.readdir(...., function(... { ... the keyword/variable this was binded to that function()'s object.. I recommend you this read: this - JavaScript | MDN

That binding does not happen with arrow functions, so, if you're curious there's another fix for your problem. You would need to replace function (err, files) with (err, files) =>, like this:

DataHandler.prototype.checkDB = function() {
    return new Promise((resolve, reject) => {
        fs.readdir('./database', (err, files) => {
            if (err) {
                if (err.code = 'ENOENT') {
                    fs.mkdir('./database', () => {
                        return this.checkDB;
                    })
                } else {
                    reject();
                }
            }
            if (files) {
                console.log(files)
            }
        })
    })
}

CodePudding user response:

Seems like the object this refers to the Object created with the new Promise(.. I would suggest to log.console(this) and check what it contains

  • Related