client.on is not a function (not discord.js related)

I'm creating my own package that needs to do some emitting from the package to the main file.

This simplified module gets what I'm trying to achieve:

const fetch = require("node-fetch")

module.exports.client = async function(username,password,version) {

    // Do login code here
    this.emit("login", loginData)
}

Then my test code runs that with

var client = new require("../index").client("username","password","0.774")

client.on("login",function(data) {
    console.log(data)
})

With every time, the program returning

client.on("login",function(data) {
       ^

TypeError: client.on is not a function

Has anyone had a similar issue? This is my first time making a module in this style, so please let me know.

Thank you!


Because your function client() exported from index.js is declared with the async keyword, it will return a Promise rather than an actual value passed to the return statement. Assuming the value you return from the function client() is an object with an on() function, then in order to access this function you either need to await the result of client() or you need to use the .then() function on promise. Example:

var clientPromise = new require("../index").client("username","password","0.774")

clientPromise.then(client => {
  client.on("login",function(data) {
    console.log(data)
  })
});

While you could also use await on the result of the client() function, this is not allowed in all contexts, and so you would have to wrap the code that does this in another async function.