Note that there are some explanatory texts on larger screens.

plurals
  1. POFunctionscope and Callbacks in Node.js
    primarykey
    data
    text
    <p>so i have to calculate some <code>share</code> in a loop. In every iteration of that loop i have to get a variable called <code>rent</code> from an array. So i devided the <code>calculate</code> function from the database stuff.</p> <pre><code>var calculate = function() { while(count &lt; 100) { var share = 50; var shareArray = []; for(var i = 0; i &lt; 100; i++) { var pension = share*2; // mathematical stuff // Gets a rent from a database and returns it in a callback getRent(modules, share, function(rent) { share = rent*foo; // some fancy mathematical stuff going on here // I need to get the share variable above out of its function scope }); // I need the share variable right here shareArray.push(share); // the value of share will be for i = 0: 50, i= 1: 50 ... // This is not what i want, i need the share value from getRent() } count++; } } </code></pre> <p>Now as you may see i am presented with the following trouble. Because I'm working in node.js, the only way to get the <code>rent</code> variable from the modules array is through this callback function called <code>getRent()</code>. The thing is, i need the <code>share</code> value after this step but outside of <code>getRent()</code>. Is there any way i can do this?</p> <p>This is the <code>getRent()</code> - Function:</p> <pre><code>var getRent = function(modules, share, callback) { // Searching for a fitting rent in the modules array // Just assume this is happening here callback(rent); }; </code></pre> <p>So the question is: How can i "return" <code>share</code>:</p> <pre><code>getRent(modules, share, function(rent) { share = rent*foo; // some fancy mathematical stuff going on here // I need to get the share variable above out of its function scope }); </code></pre> <p>in any way?</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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