Rafaqat Ali
Rafaqat Ali

Reputation: 102

Calling a function return Promise

I was trying to implement Promises when I get error saying

TypeError: productService.getSwapItems is not a function

I have created a DB class as

const mysql = require('mysql')

class Database {
    constructor( config ) {
        this.connection = mysql.createConnection( config );
    }

    query(sql, args) {
        return new Promise( (resolve, reject) => {
            this.connection.query(sql, args, (error, result) => {
                if(error) {
                    return reject(error);
                }
                resolve(result);
            });
        });
    }

    close() {
        return new Promise( (resolve, reject) => {
            this.connection.end( err => {
                if(err) {
                    return reject(err);
                }
                resolve();
            })
        });
    }
}

module.exports = Database;

And then a service class

let Database = require('./mysql.db');

const database = new Database({
    host: "db-host",
    user: "username",
    password: "password",
    database: "databasename"
});

class ProductService {
    getSwapItems(item_ids_array) {
        this.queryStr = "SELECT * FROM Item WHERE from_item_id IN (" + item_ids_array + ")";
        return database.query(this.queryStr, null); // database.query returns a promise, so getSwapItems() will also return promise??
    }
}

module.exports = ProductService;

When productService using code below, I get error.

var item_ids_array = <Array Values>;
productService.getSwapItems(item_ids_array)
.then( rows => {
    console.log(rows);
}).catch( err => {
    console.log(err);
});

Error is

productService.getSwapItems(item_ids_array)
  TypeError: productService.getSwapItems is not a function

Upvotes: 0

Views: 42

Answers (1)

raina77ow
raina77ow

Reputation: 106483

Your module exports a class ProductService with regular method getSwapItems. Classes are first-class citizens in JS, so you can assign them (as value) to any variable any way you like - including require-ing a module.

const ProductService = require('./db/product.service');

But the class is like a recipe for creating an instance of the class you can use, not an instance of the class itself. To actually create an instance of the class, use the new keyword:

const productService = new ProductService();

Only after that you'll be able to use methods of this class the usual way.

Upvotes: 2

Related Questions