title: share mqtt client object between files
body: <p>I connect to MQTT this way:</p>
  
  <pre><code>//mqtt.js
  
  const mqtt = require('mqtt');
  
  var options = {
      //needed options
  };
  
  var client = mqtt.connect('mqtt://someURL', options);
  
  client.on('connect', () =&gt; {
      console.log('Connected to MQTT server');
  });
  </code></pre>
  
  <p>I want to export the <strong>client</strong> object this way:</p>
  
  <pre><code>//mqtt.js
  
  module.exports = client;
  </code></pre>
  
  <p>So that I can import it in other files and make use of it this way:</p>
  
  <pre><code>//anotherFile.js    
  
  const client = require('./mqtt');
  client.publish(...)
  </code></pre>
  
  <p>However, we all know that this will not work! How can I achieve this ?</p>
  
  <p><strong>Update</strong></p>
  
  <p>I tried <strong>promise</strong> and get a very strange behavior. When I use the promise in the same file (mqtt.js) like the code below, everything is OK:</p>
  
  <pre><code>//mqtt.js
  const mqtt = require('mqtt');
  
  var mqttPromise = new Promise(function (resolve, reject) {
  
      var options = {
       //needed options
      };
      var client = mqtt.connect('mqtt://someURL', options);
  
      client.on('connect', () =&gt; {
          client.subscribe('#', (err) =&gt; {
              if (!err) {
                  console.log('Connected to MQTT server');
                  resolve(client);
              } else {
                  console.log('Error: ' + err);
                  reject(err);
              }
          });
      });
  });
  
  
  mqttPromise.then(function (client) {
      //do sth with client
  }, function (err) {
      console.log('Error: ' + err);
  });
  </code></pre>
  
  <p>But when I export the promise and use it in another file, like this:</p>
  
  <pre><code>//mqtt.js
  
  //same code to create the promise    
  module.exports = mqttPromise;
  
  //anotherFile.js
  
  const mqttPromise = require('./mqtt');
  
  mqttPromise.then(function (client) {
       //do sth with client
   }, function (err) {
      console.log('Error: ' + err);
   });
  </code></pre>
  
  <p>I get this error:</p>
  
  <blockquote>
    <p>TypeError: mqttPromise.then is not a function</p>
  </blockquote>