0

I have done one project where I used one callback so far, but with a bigger code base I already have chaos in it. I would like to move on to something new, specifically on async functions.

I'm using an oop pattern, so I'd like this to be implemented right into the oop. The problem is that, I've never done this before and I don't know how to do it. I have some basic code with a callback. Could anyone change this to an async function, please?

server.js

const object = require("./object");

new object(userID).name((data) => {
  console.log(data);
});

object.js

module.exports = class{

  constructor(userID){
    this.id = userID;
  }

  name(callback){
    mysqli.query("SELECT meno FROM uzivatelia WHERE id='"+ this.id +"'", (err, user) => {
      callback(user[0].meno);
    });
  }

}
ProgrammerPer
  • 1,125
  • 1
  • 11
  • 26
Styx25
  • 67
  • 4

2 Answers2

3

What @Tom suggested is correct. Another option is to use node's util.promisify, which achieves the same thing but is a little terser.

const util = require('util');
const mysqliQueryP = util.promisify(mysqli.query);

module.exports = class{

  constructor(userID){
    this.id = userID;
  }

  name() {
    return mysqliQueryP("SELECT meno FROM uzivatelia WHERE id='"+ this.id +"'");
  }

}

Melbourne2991
  • 11,707
  • 12
  • 44
  • 82
2

Return an explicit Promise that you wire into the mysqli callback pattern:

module.exports = class {

    constructor(userID) {
        this.id = userID;
    }

    name() {
        return new Promise((resolve, reject) => {
            mysqli.query(
                `SELECT meno FROM uzivatelia WHERE id = '${this.id}'`,
                (error, record) => error ? reject(error) : resolve(record)
            )
        })
    }

}

You could also add async before the method definition, but I think that won't have any impact -- the method becomes asynchronous when you return a Promise whether or not you declare it using async, and calling code will be able to await it.

const User = require('./user.js')

async testIt() {
    const myUser = new User(12345)
    const username = await myUser.name()
    console.log(username)
}

testIt()

A couple of general tips. First, to make stacktraces clear, you're going to want to name this class.

Second, it might be worth your while to investigate a solution for de-node-ifying your mysqli calls across the board. I would be very surprised if something like that doesn't already exist. If it doesn't, you could pretty easily build something small that covers the cases you need most.

Tom
  • 8,509
  • 7
  • 49
  • 78