Add delay to on('data') execution in Node.js
<p>I have this function. Basically it searches data from database and does something with it. In this demo it just increases counter.</p>

<pre><code>exports.fullThreads = function(){
  return new Promise((resolve, reject) =&gt; {
    MongoClient.connect(mongoUrl, (err, db) =&gt; {
      var fullThreads = db.collection('tmp_fullThreads'),
          threadPages = db.collection('tmp_threadPages').find();

      var counter = 0;

      threadPages.on('data', (doc) =&gt; {
        setTimeout(function(){
          counter++;
        }, 200)
      });

      threadPages.on('end', () =&gt; {
        console.log('end');
        console.log(counter);
      });

    });//connect
  });//promise
}//fullthreads
</code></pre>

<p>In this example I expected that it would call for data, wait 200ms, and then increase counter. Once it reaches the end, it would end. However it is different. <code>on('end')</code> is called before <code>on('data')</code> actually finished. I guess that is because it didn't return value immediately. So this <code>setTimeout</code> function is not a way to go. However I have a real problem here. This is simply way too fast and in real life code, this wouldn't increase counter, it would call foreign API which doesn't accept so many calls in so little time, so I wanted to make a delay between each call, how is this done properly?   </p>