2016-09-27 63 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循環。