Return an object when the promise finishes inside a require

158 views Asked by At

When i was writing this promise to query an sql datbase i was not testing it with require i was just running the js file straight from node in the console. Now i need it to return the data when finishing the loop and I can't figure out how. Promises as well as reading data from an SQL are both new to me so i was happy to have gotten it working. But now when i require this code with

var dbData = new getDataSQL();

it returns {} instead of a nice big chunk of data. It finishes its promises but the data is not returned. Any ideas on how best to return the data?

module.exports = function getDataSQL(){
//JSON OBJECTS
var dates = require('./JSON/dates.js');
var companies = require('./JSON/companies.js');
//SQL FUNCTION
var sqlConJS = require('./sqlCon.js');

function fn(retVal, i, startDate, endDate){
    data[i] = JSON.parse(retVal);
    var total = 0;
        for(var b = 0; b<Object.keys(data[i].result).length;b++){
            total = total + data[i].result[b].Amount
        }
        data[i].totalAmount = total;
        data[i].startDate = startDate;
        data[i].endDate = endDate;
    console.log("No= "+i,"Reccs= " + Object.keys(data[i].result).length,"StartDate=" + startDate,"EndDate=" + endDate, "Amount = " + Math.floor(total));
    dataP();
}
//INIT SQL QUERY
var data = [];
var incrDat = 0;
var dataPromise = function(i){
    return new Promise(function(resolve, reject){
        data[i]={};
        var sqlCon = new sqlConJS(fn, dates[i].startDate, dates[i].endDate, companies[9].company, i);
        if(dates.length===i)reject();
        else resolve();
    });
};
var dataP = function(){
    dataPromise(incrDat++).then().catch(function(){
        console.log("done!");
        console.log(data[0].result[0]["Posting Date"]);
        return data;
    });
}
dataP();
}
1

There are 1 answers

0
WouldBeNerd On

Never mind i got it, callback function offcourse! I have so much to learn still. Add cbRetData when declaring the function at the top.

module.exports = function getDataSQL(cbRetData){

under Console.log("done!"); i put

cbRetData(data);

in the main js script we create the function cbRetData like so

function cbRetData(retData){
    dbData = retData;
    console.log("retData to dbData coming in!");
    console.log(dbData);
}

where we call the getDataSQL function after requiring it u simply pass the function cbRetData along like so.

var getdbData = new getDataSQL(cbRetData);

I'm only just beginning to come to terms with callback functions and such.