0

First of I have a class of Drug declared:

// Classes

// __Drug
class Drug {

    constructor(id, name, form, ppv, stock) {
        this.id = id
        this.name = name
        this.form = form
        this.ppv = ppv
        this.stock = stock
    }

}

Next, I have a class of Search:

// __Search
class Search {

    constructor(query = null) {
        this.query = query
        this.results = []
    }

    // Searches for the query in the database and limits the search results
    forQuery(limit = 10) {
        let sqlQuery = `SELECT db_drug_id, db_drug_name, db_drug_form,  db_drug_ppv, db_drug_stock FROM drugs WHERE db_drug_name LIKE "${this.query}%" LIMIT ${limit}`
        connection.query(sqlQuery, (errors, results) => {
            if (errors) throw errors
            for (let i in results) {
                this["results"].push(new Drug(results[i].db_drug_id, results[i].db_drug_name, results[i].db_drug_form, results[i].db_drug_ppv, results[i].db_drug_stock))
            }
            console.log(this.results) // This logs after the second console.log
        })
        console.log(this.results)
    }

}

Within connection.query the console.log(this.results) logs:

enter image description here

The Next second console.log(this.results) logs: enter image description here

I can't access it's contents with this.results[i]. I wish to create another method to append these results to the DOM. When defining it I will be faced with the problem of not being able to access it. I don't to access it from an instance of Search.

And this is how I call the methods.

// Document
$(document).ready(function() {

    // Listens for any change in the search input field
    $('#search-input').on('input', function() { 
        search = new Search($("#search-input").val())
        search.forQuery(10)
    })

})
Mohamed Seif Khalid
  • 555
  • 1
  • 4
  • 14
  • You should access it using `search.results[i]` – vijayst Jun 17 '18 at 16:19
  • @vijayst I wish to create another method to append these results to the DOM. When defining it I will be faced with the problem of not being able to access it. I don't to access it from an instance of Search. – Mohamed Seif Khalid Jun 17 '18 at 16:27
  • You should probably have `forQuery` return a promise so you can append results to the DOM when your request resolves. – Damon Jun 17 '18 at 16:29

0 Answers0