shivshankar
shivshankar

Reputation: 2135

async call to database for loop not wait

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

Upvotes: 0

Views: 57

Answers (2)

MukeshRKrish
MukeshRKrish

Reputation: 1090

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

Upvotes: 1

Rayon
Rayon

Reputation: 36609

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);
  });
}

Upvotes: 2

Related Questions