Use of "Return" in module.Exports

Asked

Viewed 162 times

1

I am developing a project in Nodejs and at the moment, I am facing some problems when returning some value of a function within a module.

Code:

Archive for queries

async function query(query){
    con.connect(function(err) {
        if (err) throw err;
        con.query(query, function (err, result) {
            if (err) throw err;
            const response = {
                status: true,
                data: result
            };
            return response;
        });
    });
}

// Teoricamente, era para a função query() retornar um JSON ao chamá-la

module.exports = query;

Controller file

const conn = require('../sealed/con');
module.exports = {
    async index(request, response){
        const splans = await(conn(`SELECT * FROM table`));
        console.log(splans);
    }
};

When calling the function within my controller, it is returned only undefined, but if I give a console.log in function query, works normally, the problem is that I need these values returned in my controller.

1 answer

2


Your job query is not asynchronous in a modern way, but rather via callback. So you have to encapsulate the function in a Promise and call the resolve of Promise when callbacks are called.

You can do it like this:

async function query(query) {
  return new Promise((res, rej) => {
    con.connect(function(err) {
      if (err) throw err;
      con.query(query, function(err, result) {
        if (err) return rej(err);
        const response = {
          status: true,
          data: result
        };
        res(response);
      });
    });
  });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.