Wednesday 17 May 2017

Nodejs how to access callback variable outside the function

This is my code want to access callback variable newID outside calling-function   
for (var i = 0; i < sizeOfResult; ++i) {
    var newKey = {};     <!--   Main  json array -->
    newKey = {
        date: result[i]['date'],
        issue: result[i]['issue'],
        status: result[i]['status']
    };
    getNextSequenceValue("inventoryid",db, function(err, newID) {
        if(err){
            console.log(err);
        }
        newKey["_id"] = newID;     /* try to add/assign callback*/  

variable(newID) into newKey }); console.log("newKey: %j", newKey); /* but unable to get access */ callback variable(newID) here batch.insert(newKey); }

function getNextSequenceValue(name,db,callback) {
    var ret = db.collection('counters_inv').findAndModify(
        { _id: name },
        null,
        { $inc: { sequence_value: 1 } },
        {new: true},
        function(err,doc) {
            if(err){
                return callback(err)
            }
            callback(null, doc.value.sequence_value);
            });
}



via Ramesh Chand

No comments:

Post a Comment