0

I have a offer.js file which does this:

const mssql = require('mssql/msnodesqlv8'); // mssql npm package with msnodesqlv8 for windows authentication to work


exports.rsOffersAll = function () {
    global.MYDB.connect(function (error) {   //MYDB is a connectionPool created as a global variable in app.js
        if (error) {
            console.log(error);
            return;
        }
        global.MYDB.request(MYDB).query('SELECT Top(10) * FROM [dbo].[Offer]', function (error, result) {
            if (error) {
                console.log(error);
            } else {
                return(result); // I want this result to be sent to any page that asks for it
            }
            MYDB.close();
        });
    });
};

I have another file called index.js (which will eventually be an Express controller/router) and so far I just do this:

const Offer = require('../models/offer'); // this is the `offer.js` page above

var result = Offer.rsOffersAll();
console.log(result); // this shows in the console as "undefined"

How do I get the result from offer.js in my index.js file so that I can use it? Why is it undefined? Can someone PLEASE explain it to me like I'm a 5-year old because I don't understand why such a basic thing does not work.

volume one
  • 6,800
  • 13
  • 67
  • 146
  • 1
    you are not returning anything in `exports.rsOffersAll` - but the code in that function performs asynchronous requests - so, you'll need to deal with that code like you would any other asynchronous code ... callback or promise – Bravo Nov 16 '19 at 21:14
  • @Bravo can you please explain because I dont understand what you mean or how to fix it – volume one Nov 16 '19 at 21:14
  • node is riddled with the callback pattern, and `async`'s `waterfall` or https://www.npmjs.com/package/async-waterfall can make it feel a little more "normal". Or you can choose a different language. – erik258 Nov 16 '19 at 21:18
  • @bravo how do I do that? – volume one Nov 16 '19 at 22:11

0 Answers0