Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

46
Views
How to get data from inside a response function in Nods js

Im a new user of Nodejs and Javascript

I have this class :

class Users {
    constructor() {
        this.all;
        this.selectAll();
    }
    async selectAll() {
      await connection.connect(() =>
            connection.query(`SELECT * FROM users`, (err, result) => {
                this.setData(result);
            }),
        );
    }

    setData(res) {
        this.all = res;
    }
}

I want to get result of data from the response function selectAll(); for example:

var db = new Users();
console.log(db.all);

I expected db.all to give me result of selectAll()

Is there any better idea?

7 months ago · Santiago Trujillo
1 answers
Answer question

0

You want to await this.selectAll seeing as it is a promise. So you need to make sure it returns a promise. You could make the constructor async to await the selectAll but this is not advised and probably won't work.

Personally, I would just call db.selectAll after creating the instance of users.

Maybe something like this:

File: Users.js

export class Users {
    all = null

    async selectAll() {
        return connection.connect(() =>
            connection.query(`SELECT * FROM users`, (err, result) => {
                this.setData(result);
            })
        );
    }

    setData(res) {
        this.all = res;
    }
}

File: index.js (or anywhere else)

import { Users } from './Users.js'

// Somewhere else in your code in an async function:
const anotherPlace = async () => {
    const db = new Users();
    await db.selectAll();
    console.log(db.all)
}
7 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.