I am trying to write an API with nodejs following an OO pattern, but I am having a problem returning the data from the class to my method. more specifically, I have created a parent class and a child class that extends the parent and then I make a request from a function inside of another file. if I print the result inside the class it gives me the right result but when I get the response I get undefined... I know this is due to async calls, but I dont really know how to fix it. in other words can I use promises or callback to wait for the response and if so how can I do it?.

I've tried setting up a callback on the parent class and the file making the request, I have tried using .then(rows) but it doesnt work,

in the parent class I have something like.. where tablename and findBylike are methods on the child class.

static find(conditions) {
        const queryString = `SELECT * FROM ${this.tableName()} WHERE ${this.findBylike(conditions)}`;
        console.log(queryString);
        db.query(queryString, (error, result) => {
            if (error) {
                console.log("result " + error)
                return error;
            } else {
                console.log("result " + result)
                return result;
            }
        })
    }

in the child class I have

    static tableName() {
        return 'listing';
    }

    static columns() {
        return ['name', 'description', 'owner'];
    }

    // Other Listing specific logic goes here
    static findBylike(name) {
        return this.find(`name LIKE '%${name}%' AND status = true`);
    }

and then I make the call in a function like

router.get('/search', (request, response) => {
    console.log(request.query.like);
    Listing.find(request.query.like).then(result => {
        if (err) {
            console.log("Error completing game: " + err);
            response.sendStatus(500);
        } else {
            response.send(result);
        }
    })

on this last part I get undefined whereas I want to get the result from the query.

0 Answers