0
嘗試從redis讀取數據然後以json格式將其發送給用戶時,我無法獲得正確的輸出。nodejs async.parallel工作不正常
這是我的代碼
//API to get slot for a particular date range
app.get('/listcapacity/:ticketid/:fromdate/:todate', function(req, res) {
var id = req.params.ticketid;
var fromdate = req.params.fromdate;
var todate = req.params.todate;
var result = {};
var data_output = [];
var asyncTasks = [];
var currentDate = new Date(fromdate);
var between = [];
var end = new Date(todate);
while (currentDate <= end) {
var tempdate = new Date(currentDate).toISOString();
var dump = tempdate.toString().split("T");
between.push(dump[0]);
currentDate.setDate(currentDate.getDate() + 1);
}
between.forEach(function(entry) {
asyncTasks.push(function(callback) {
client.exists(id+entry, function (err, reply) {
if (reply === 1) {
console.log("Found");
client.get(id+entry, function (err, reply) {
var output = JSON.parse(reply);
data_output = data_output.concat(output);
});
}
callback();
});
});
});
async.parallel(asyncTasks, function(){
// All tasks are done now
result['data'] = data_output;
result['response'] = 1;
result['message'] = 'vacancies list fetched successfully!';
res.json(result);
});
});
我總是得到輸出{"data":[],"response":1,"message":"vacancies list fetched successfully!"}
即使我已經檢查密鑰是那裏的Redis它總是由應用程序找到了。 由於某些原因,redis部分在數據發送給用戶之後得到執行。這是爲什麼發生?我知道redis在async中工作,因此使用async.parallel函數來處理這個問題,但即使如此,我最終也遇到了同樣的問題,如果我不想使用異步的話就會遇到同樣的問題。這是什麼原因?
你應該在設置'data_output'後用連接結果調用'callback'。現在在'client.get'調用結束之前調用它 – Creynders