Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your export can't work because it is outside the function while the <code>foo</code>declaration is inside. But if you put the export inside, when you use your module you can't be sure the export was defined.</p> <p>The best way to work with an ansync system is to use callback. You need to export a callback assignation method to get the callback, and call it on the async execution.</p> <p>Example:</p> <pre><code>var foo, callback; async.function(function(response) { foo = "foobar"; if( typeof callback == 'function' ){ callback(foo); } }); module.exports = function(cb){ if(typeof foo != 'undefined'){ cb(foo); // If foo is already define, I don't wait. } else { callback = cb; } } </code></pre> <p><em>Here <code>async.function</code> is just a placeholder to symbolise an async call.</em></p> <p>In main</p> <pre><code>var fooMod = require('./foo.js'); fooMod(function(foo){ //Here code using foo; }); </code></pre> <h1>Multiple callback way</h1> <p>If your module need to be called more than once you need to manage an array of callback:</p> <pre><code>var foo, callbackList = []; async.function(function(response) { foo = "foobar"; // You can use all other form of array walk. for(var i = 0; i &lt; callbackList.length; i++){ callbackList[i](foo) } }); module.exports = function(cb){ if(typeof foo != 'undefined'){ cb(foo); // If foo is already define, I don't wait. } else { callback.push(cb); } } </code></pre> <p><em>Here <code>async.function</code> is just a placeholder to symbolise an async call.</em></p> <p>In main</p> <pre><code>var fooMod = require('./foo.js'); fooMod(function(foo){ //Here code using foo; }); </code></pre> <h1>Promise way</h1> <p>You can also use Promise to solve that. This method support multiple call by the design of the Promise:</p> <pre><code>var foo, callback; module.exports = new Promise(function(resolve, reject){ async.function(function(response) { foo = "foobar" resolve(foo); }); }); </code></pre> <p><em>Here <code>async.function</code> is just a placeholder to symbolise an async call.</em></p> <p>In main</p> <pre><code>var fooMod = require('./foo.js').then(function(foo){ //Here code using foo; }); </code></pre> <p>See <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="noreferrer" title="Promise on MDN">Promise documentation</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload