【问题标题】:How to clear array using callback in async nodejs once processing is done?处理完成后如何在异步nodejs中使用回调清除数组?
【发布时间】:2017-11-24 18:53:00
【问题描述】:

我有一个基于用户日期范围的搜索功能。有时我会看到来自服务器的结果,在某些情况下它返回空响应数组 matches

我们如何确保async.eachSeries() 已完成并将结果发送给客户端并清除数组以进行下一次搜索?我尝试申请setTimeout,但这并没有解决问题。

搜索.js

var matches;
var results = [];


// loop through each file
async.eachSeries(filesData.logFiles, function(logfile, done) {
    // read file
    readStream = fs.createReadStream('./logs/' + filesData.searchEnv + '/' + logfile.filename, 'utf8')
    readStream.pipe(split())
        .on('data', function(line) {
            if (typeof searchStr === 'string') {
                multipleStrFlag = false;
                if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) {
                    results.push({
                        filename: logfile.filename,
                        value: line
                    });

                }
            } else {
                multipleStrFlag = true;
                if (messageDateInfo - searchStartDate > 0 && searchEndDate - messageDateInfo > 0) {
                    results.push({
                        filename: logfile.filename,
                        value: line
                    });

                }

            };
        });
    done();
}, function(err) {
    if (err) {
        console.log('error', err);
    }
});

readStream.on('end', function() {
    if (multipleStrFlag) {
        var matchingCondition = function matchingCondition(_ref) {
            var itemB = _ref.itemB,
                itemA = _ref.itemA;
            return itemB.value.includes(itemA);
        };
        // filter all items from B that satisfy a matching condition with at least one item from A
        matches = results.filter(function(itemB) {
            return searchStr.every(function(itemA) {
                return matchingCondition({
                    itemB: itemB,
                    itemA: itemA
                });
            });
        });
    } else {
        matches = results;
    }
    setTimeout(function,(){
    callback(matches);
    matches = [];
    results = [];
   },1000);
 });

【问题讨论】:

    标签: javascript arrays node.js


    【解决方案1】:

    async 提供以下语法。

    eachSeries(coll, iteratee, callback)
    

    只有在所有迭代函数都完成后才会调用回调。

    使用它,您可以将回调函数更新为

    function (err){
      if(err) {//handle err}
      results = []
    }
    

    应该清除每个系列后的结果数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多