0

Where should I call module.export, I assume, it's supposed to be a callback function.

But I'm confused as to where am I supposed to call the callback function.

I'm still confused with the solution, too complicated for me.

sql.connect(config, function(err) {

  if (err)
    console.log(err);

  // create Request object
  var request = new sql.Request();

  // query to the database and get the records
  request.query('select part_num,qty from CRM.CRM.Fishbowl_Inventory where not location = \'Shipping\'',

    function(err, recordset) {

      if (err)
        console.log(err)

      // send records as a response
      var details = recordset;
    });
});

module.exports = details;

Confusion:

Extremely sorry to bother you guys but I want to be sure that I'm doing no harm to our database by involving any database request through Javascript.

I'm testing directly with our production database, hence cautious

So as Max provided in his answer the following code

const connectToSql = require('./connectToSql');

connectToSql()
    .then(details => {
        console.log(details);

    //Here I can do as much logic as I want 
    //And it won't affect my database or call multiple requests on my DB 


    })
    .catch(err => {
        console.log(err);
    });

I can understand I'm asking super silly questions, very sorry about that.

hemantmetal
  • 107
  • 10
  • @ibrahim mahrir still that answer didn't solve my problem – hemantmetal May 15 '18 at 17:06
  • @ hem.. it is the same problem. I've opened the question anyway. – ibrahim mahrir May 15 '18 at 17:10
  • 1
    Export a promise. You can't export a result that isn't there yet. – Bergi May 15 '18 at 17:35
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith May 15 '18 at 17:50
  • Asynchronous programming is hard when you first encounter it. But you can't ignore it or wish it away. Your code as you wrote it cannot work, and we are trying to explain why. We're not doing a great job of that because, again, async is hard, but there it is. – Jared Smith May 15 '18 at 17:54
  • Post-edit: your intuition is correct: the function Max wrote will query your database one time. You can store the results in a var: `var queryResult = connectToSql(config);` and can call `.then` on the resulting Promise as many times as you want without affecting the db. If you call `connectToSql` again, it will query your db again and return a Promise of *that* result. – Jared Smith May 16 '18 at 11:11
  • That's just what I needed Jared. Thank you very very much Max, @JaredSmith, Bergi and ibrahimmahrir to help me solve this problem. – hemantmetal May 16 '18 at 17:02

1 Answers1

2

You can't export the result of your function. You want to export a function that will return your value. Like this:

function connectToSql(config) {
  return new Promise((resolve, reject) => {
    sql.connect(config, function (err) {

      if (err) {
        console.log(err);
        reject(err);
      }

      // create Request object
      var request = new sql.Request();

      // query to the database and get the records
      request.query('select part_num,qty from CRM.CRM.Fishbowl_Inventory where not location = \'Shipping\'',

        function (requestErr, recordset) {

          if (err) {
            console.log(requestErr);
            reject(requestErr);
          }

          resolve(recordset);
        });
    });
  });
}

module.exports = connectToSql;

Because your function is async, I returned a promise that will return your result. Also, your second error from your query is named the same as your first error from the connection. That would cause problems.

Example of how to use this:

const connectToSql = require('./connectToSql');

connectToSql()
    .then(details => {
        console.log(details);
    })
    .catch(err => {
        console.log(err);
    });
Max Baldwin
  • 3,404
  • 3
  • 26
  • 40
  • it's returning a function, how can I fetch the object out of it? – hemantmetal May 15 '18 at 17:34
  • @hemantmetal no it's not. Your module is running `sql.connect` and then you are trying to export the result, but that is impossible. Look at my example. I'm exporting the function `connectToSql` so that you can run it in another file. Then you can handle the results there. – Max Baldwin May 15 '18 at 17:38
  • Hi @Max Baldwin, I got what you're trying to say. Is there a way so that I can save the data just in my `details` object which I assume we are transferring by `details = recordSet`. So that I can just export my **data** which is `details`. – hemantmetal May 15 '18 at 18:16
  • @hemantmetal No you can't do that because `details` and `module.exports` are not in the same scope. Also, your connection and query to your sql database are both asynchronous. – Max Baldwin May 15 '18 at 18:28
  • @hemantmetal you cannot unwrap a Promise. You cannot return synchronously from an asynchronous call. You cannot do these things for the same reason you cannot read tomorrow's newspaper today. You cannot export that data directly, because the export happens *before* the data is there. It will *always* happen before. There is no way to make it "wait" until the data is there, and that is a good thing (as it might have to wait forever while your code sits there frozen). Either export a Promise, a function that returns a Promise (== async function), or a function that takes a callback. – Jared Smith May 15 '18 at 20:37
  • @JaredSmith please look at my question edit. Thank you. – hemantmetal May 15 '18 at 23:57