title: Export value from callback in node.js
body: <p>I am building a small node.js website with a user interface that features a dropdown with a list of countries.</p>
  
  <p>Previously the list of countries was hard coded in a json file that I would read:</p>
  
  <pre><code>exports.countries = require('./json/countries.json');
  </code></pre>
  
  <p>Then I realized I shouldn't hard code it like that when I can do a <code>distinct</code> query to the the list from the mongodb database.</p>
  
  <pre><code>db.collection.distinct('c', {}, function(err, data) {
    // something
  });
  </code></pre>
  
  <p>But then there's the question of how to extract the value of the <code>data</code> variable in that callback function. I discovered that this works:</p>
  
  <pre><code>db.collection.distinct('c', {}, function(err, data) {
    if (err) {
      throw Error('mongodb problem - unable to load distinct values');
    } else {
      exports.countries = data;
    }
  });
  </code></pre>
  
  <p>I am new to node.js and this seems fishy to me. Is this OK code? Is it better do this with generators or promises? If I wanted to use generators or promises to do this, how would I do that?</p>
  
  <p>The end result where this is used is in a template. <code>ref.countries</code> is the actual list of countries using my fishy code. If I had a Promise instead of the list of countries, how would I change this code?</p>
  
  <pre><code>  &lt;% ref.countries.forEach(function(c) { -%&gt;
    &lt;option value="&lt;%= c %&gt;"&gt;
      &lt;%= ref.isoCodes[c] -%&gt;
    &lt;/option&gt;
    &lt;% }); -%&gt;
  </code></pre>
  
  <p>I am using node v6.10.3.</p>