-1

i can not figure out why my array is empty while the console is showing output:

I'm fetching data from dynamodb and trying to make a modified response json array i can print the values of dynamodb response but when i push it into array the returned array is empty here is my code.

Here is Util.js file

const dynamo = require('./dynamo.js')
var myjson = [];
exports.myjson = [];
exports.maketimetabledata = function(callback) {


    var table = "timetable";
    for (i = 1; i <= 2; i++) {
        dynamo.docClient.get({
            TableName: table,
            Key: {
                "id": i
            }
        }, function(err, data) {
            if (err) {
                console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
                return err;
            } else {
                dynamores = JSON.parse(JSON.stringify(data));
                myjson.push(i);
            }
        });

        console.log(myjson);

    }

    callback("done");

};

and here is my partial index file:

app.get('/', (req, res) => {
    var myjson = [];
    util.maketimetabledata(function(returnvalue) {
        if (returnvalue) {
            console.log(util.myjson);
        }
    });
});

output :

[] [] [] 
undefined 
{ response from dynamo db for debugging purpose}
Satpal
  • 132,252
  • 13
  • 159
  • 168
varnit
  • 1,859
  • 10
  • 21
  • [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) really should have been the first duplicate suggestion on the list when you typed the title. It's almost right up the top of google search results directly from the title you chose here. You should always check and read those first. If you do find them and don't understand them, then mention it. – Neil Lunn Apr 27 '18 at 10:54
  • thanks @satpal but i'm already using the async technique given in the link but still i'm getting blank array can you please help me understand what exactly is wrong with my program – varnit Apr 27 '18 at 11:19
  • thanks @satpal my issue is solved now and because of you i have learned the power of javascript promises – varnit Apr 27 '18 at 12:15

1 Answers1

0

Assuming dynamo.docClient.get() returns a Promise, You can use Promise.all() to wait for all the promise to complete then invoke the callback method.

//Use Promise.all()
exports.maketimetabledata = function (callback) {
    var table = "timetable";
    for (i = 1; i <= 2; i++) {
        var table = "timetable";
        var promiseArray = [];
        for (i = 1; i <= 2; i++) {
            var promise = dynamo.docClient.get({
                    //Your code
                });
            promiseArray.push(promise)
        }

        console.log(myjson);
    }
    Promise.all(promiseArray).then(function () {
        callback(myjson);
    });

};



//Usage
util.maketimetabledata(function (myjson) {
    if (returnvalue) {
        console.log(myjson);
    }
});

If the method is not returning Promise

var promise = new Promise(function (resolve, reject) {
    dynamo.docClient.get({
        TableName: table,
        Key: {
            "id": i
        }
    }, function (err, data) {
        if (err) {
            console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));

            reject();
            return err;
        } else {
            dynamores = JSON.parse(JSON.stringify(data));
            myjson.push(i);

            resolve();
        }
    });
});
Satpal
  • 132,252
  • 13
  • 159
  • 168