知道什么时候异步foreach内部异步已经完成

时间:2016-01-10 01:24:09

标签: javascript node.js asynchronous

我在node.js中使用异步库,我在另一个async.forEach调用中有一个async.forEach调用,我需要知道异步调用 s 何时完全完成处理。

代码示例:

var content = '...';
var resultArr = [];

async.each(regexArr, function(regex) {
        var matches = content.match(regex);
        async.each(matches, function(match) {
            var result = regex.exec(match);
            regex.lastIndex = 0;
            resultArr.push(result[1]);
        });
    }, function(err) {
        // I need to know when ALL inner async.forEach finished processing 
        // for ALL outside async.forEach and then do something with the resultArr
    });

1 个答案:

答案 0 :(得分:1)

您可以使用async.map和其他回调强制同步来处理内部回调结果的集合。

尽管如此,使用JS,执行是在一个线程上,正如其他人所说,所以我首先包含了MUCH更简单的同步版本。

// Synchronous version is just as good for Regex stuff.
var content = '...';
var resultArr = [].concat.apply([], regexArr.map(function(regex) {
    return (content.match(regex) || []).map(function(match) {
        return (regex.exec(match) || [])[1];
    });
}));

    // IN THIS EXAMPLE, SYNCHRONOUS WOULD WORK TOO...


    var content = '...';
    collectRegexResults(content, regexArr, function(err, flatRegexResults) {
        // Handle errors.
        // flatRegexResults is equivalent to resultArr
        //    from your question.
    });

    function collectSingleRegexFor(content) {
        return function(regex, passBackGroup) {
            var matches = content.match(regex);
            // Note use of || [] if match is null
            async.map(matches || [], function(match, finishSingle) {
                try {
                    finishSingle(null, regex.exec(match)[1]);
                } catch (err) {
                    finishSingle(err, null);
                }
            }, passBackGroup); // Submits to outer as regexSets element
        };
    }

    function collectRegexResults(text, regexArr, doStuffPostComplete) {
        async.map(regexArr, collectSingleRegexFor(text), function(err, regexSets) {
            if (err) {
                return doStuffPostComplete(err);
            }
            // Flattening the Array again.
            doStuffPostComplete(null, [].concat.apply([], regexSets));
        });
    }