nodejs async.parallel无法正常工作

时间:2016-10-04 12:12:46

标签: node.js asynchronous

尝试从redis读取数据然后以json格式将其发送给用户时,无法获得正确的输出。

这是我的代码

//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.parallel函数来处理这个问题,但即便如此,如果我不使用异步,我会遇到同样的问题。这是什么原因?

1 个答案:

答案 0 :(得分:0)

unset($a); unlink($nomeZip); 是异步操作,你必须在那里回调。此外,您还需要一个else语句,并且还需要回调:

client.get