0

I'm simply trying to access database while parsing json. This small block of code making my life hell

function loopColumns(val, cb){
    db.one('select tag_name from t_tag where tag_id = $1', val)
    .then(function (data) {
        //console.log(data.tag_name)
        cb(null, data.tag_name)
    });

}

var value = {"Travel Activity":[1,2], "Travel style":[3,4]};

for( i in value){ 
    //console.log(value[i], i)
    var output = '';
    var outcome = '';
    var str = value[i];
    for(j in str){
        loopColumns(str[j], function(err,res){
            if(outcome=='') outcome= res;
            else outcome= outcome+' , '+res;
            console.log(outcome);
        })

    }

    var output = i+' : '+outcome+' \n';
    console.log('output \n'+output);
};

this comes output
output Travel Activity :
output Travel style :
good food
good food , Hicking
good food , Hicking , xyz
good food , Hicking , xyz , test

I like to get output as
Travel style : good food, Hicking
Travel Activity : xyz , test

Plz save my life

4
  • Use Promise.. Commented Sep 27, 2016 at 6:09
  • Remove duplicate declaration of var output Commented Sep 27, 2016 at 6:10
  • i'm already using promise, it's problem of async behavior Commented Sep 27, 2016 at 6:47
  • You are suppose to provide complete example... Incomplete code will not help the cause... Commented Sep 27, 2016 at 6:48

2 Answers 2

2

Use Promise.all

The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved.

Use for-loop instead of for-in loop to iterate array

function loopColumns(val, cb) {
  db.one('select tag_name from t_tag where tag_id = $1', val)
    .then(function(data) {
      cb(null, data.tag_name)
    });
}
var value = {
  "Travel Activity": [1, 2],
  "Travel style": [3, 4]
};
for (var i in value) {
  var output = '';
  var promiseArr = [];
  for (var j = 0, len = value[i].length; j < len; j++) {
    var promise = new Promise(function(resolve) {
      loopColumns(value[i], function(err, res) {
        resolve(res);
      });
    });
    promiseArr.push(promise);
  }
  Promise.all(promiseArr).then(function(arr) {
    var op = arr.join(', ');
    output += i + ' : ' + op + ' \n';
    console.log('output \n' + output);
  });
}

Sign up to request clarification or add additional context in comments.

3 Comments

@shivshankar — I'm glad it helped! Happy Coding
help me plz to access output variable outside for-in loop to export other module
@shivshankar – Your module function should have a callback
1

Use each from async utility module instead of using for loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.