Node.js: How do you handle callbacks in a loop?
<p>I'm using Node.js and Box SDK.  My (failing!) code looks like this:</p>

<pre><code>var connection = box.getConnection(req.user.login);
connection.ready(function () {
  connection.getFolderItems(0, null, function (err, result) {
    if (err) {
      opts.body = err;
    } else {
      opts.body = result;
      var a = [];
      for (var i=0; i &lt; result.entries.length; i++) {
        connection.getFileInfo(result.entries[i].id, function (err, fileInfo) {
        if (err) {
          opts.body = err;
        } else {
          a.push(fileInfo);
        }
      });}
    }
</code></pre>

<p>In "procedural" terms, this is which I'm trying to do:</p>

<pre><code>var connection= box.getConnection()
var items = connection.getFolderItems()
var itemList = new List
foreach (item in items) {
  connection.getFileInfo(item.id)
  itemList.add(item)
}
display(itemList)
</code></pre>

<p>My problem is that <code>connection.getFolderItems()</code> and <code>connection.getFileInfo()</code> are asynchronous - the "for" loop exits before all the results are returned.</p>

<p>Q: What is the best way in Node.js to 1) get the result of the first async call, 2) iterate through the list, making more async calls, and 3) process the results when everything is "done".</p>

<p>Q: Are <a href="https://www.npmjs.com/package/promise" rel="noreferrer">promises</a> a good choice here?</p>

<p>Q: Is <a href="https://stackoverflow.com/questions/26164837/difference-between-done-and-next-in-node-js-callbacks">done()/next()</a> an option?</p>

<p>Q: Is there any "standard idiom" in Node.js for this kind of scenario?</p>