sending a streaming response to a REST query with async operation
<p><strong><em>update:</strong> clarified and edited code to reflect what I <strong>really</strong> want, that is, send a streaming response, that is, send back matched results as they arrive from their own <code>async</code> matching process.</em></p>

<p>consider (using <code>expressjs</code>-ish code)</p>

<pre><code>app.post('/', jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400)

    // matches is not needed for this scenario so
    // commenting it out
    // var matches = [];
    req.body.forEach(function(element, index) {

        foo.match(
            element, 
            function callback(error, result) {
                if (error) {
                    console.log(error); // on error 
                }
                else {
                    ⇒ if (some condition) {
                        // matches.push(result);
                        ⇒ res.send(result);
                    }
                }
            }
        );
    });

    // moved this above, inside the callback
    // ⇒ res.send(matches);

});
</code></pre>

<p>The input to <code>post('/')</code> is an array of terms. Each term is matched using <code>foo</code> which has a <code>callback</code> after every call. I want to send back all the matches that satisfy "some condition" (see <strong>⇒</strong> in the code above). Ideally, it would be good to send back a streaming response, that is, send a response back as the matches occur (because <code>foo.match()</code> might take a while for each term). How do I go about this?</p>