2016-09-27 65 views
0

我只是试图访问数据库,而解析json。这个代码小块使我生命地狱
异步调用数据库for循环不等

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值= { “旅行活动”:[1,2], “旅游风格”:[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); 
}; 

这是以输出
输出 旅游活动:
输出 旅行风格:
好吃
好食物,Hicking
良好的食物,Hicking,XYZ
良好的食物,Hicking,XYZ ,测试

我想获得输出
旅行风格:良好的食物,Hicking
旅游活动:XYZ,测试

PLZ救我的命

+0

使用'承诺'.. – Rayon

+0

删除'var output'的重复声明 – Rayon

+0

我已经在使用承诺,它是异步行为的问题 – shivshankar

回答

2

使用Promise.all

Promise.all( iterable)方法返回一个promise,它解析了迭代参数中的所有promise都解决了。

使用for-loop,而不是for-in循环迭代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); 
 
    }); 
 
}

+1

它的工作。谢谢人造丝:) – shivshankar

+0

@shivshankar - 我很高兴它帮助! _Happy Coding_ – Rayon

+0

帮助我PLZ访问输出变量外部for-in循环来导出其他模块 – shivshankar

1

使用eachasync实用模块,而不是使用for循环。