title: Maintaining Context In Asynchronous JS: web3.eth.getBalance() as Example
body: <p>I'm currently working with nodejs and web3, and running into problems with the asynchronous model, and perhaps the specific implementation of web3's calls.  The code below will provide my specific problem, and I believe the answer will be a pattern that can be used elsewhere.</p>
  
  <p>The core question: how do I get the balance using the getBalance request while retaining context of the account for which I queried? </p>
  
  <p>Code simplified for brevity.</p>
  
  <p>I have a list:</p>
  
  <pre><code>var ethAccounts = ['0xabc', '0xdef', '0x123'];
  </code></pre>
  
  <p>My code will iterate through the list, getting the balance of each and doing something with it.  Simple, right?  I can use getBalance(), prototyped as:</p>
  
  <pre><code>web3.eth.getBalance( account, blockNumber(optional), callback (optional)  )
  </code></pre>
  
  <p>The catch: getBalance is an asynchronous call that returns a Promise.</p>
  
  <pre><code>var balance = web3.eth.getBalance( ethAccounts[0] );
  </code></pre>
  
  <p>.. balance won't be what I need when it returns.</p>
  
  <p>The official guidance is:</p>
  
  <pre><code>web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1")
  .then(console.log);
  &gt; "1000000000000"
  </code></pre>
  
  <p>I don't need the value at the console, so I build a function to catch the value.</p>
  
  <pre><code>web3.eth.getBalance(ethAccounts[0]).then( 
      function( value ) { 
          var balance = value; 
  
          // In this scope, I *can't see* ethAccounts[0]
  
          console.log(balance);
      } 
  );
  </code></pre>
  
  <p>In my function block, I need <em>both</em> the account and the value.</p>
  
  <p>Perhaps the callback can help:</p>
  
  <pre><code> function testCallback( value1, value2 ) {
       console.log(value1 + ", " + value2 );
   }
   web3.eth.getBalance(ethAccounts[0], undefined, testCallback );
  </code></pre>
  
  <p>Console output will be:</p>
  
  <pre><code>100000000000000000000, undefined
  </code></pre>
  
  <p>I have tried a number of scenarios: adding parameters to the callback, to the handler function, trying to cheat the promise with "await".  So far I don't have a single pattern through which I can retain context.</p>
  
  <p>Am I missing a simple Javascript of asynchronous pattern?  How can I receive the balance in the same scope as I have the account in the request?</p>
  
  <p>Thanks much!</p>