title: How to avoid async.waterfall "TypeError: Cannot read property of undefined"?
body: <p>I am working on an async.waterfall that I am unsure of how to avoid: "TypeError: Cannot read property 'MediaUrl' of undefined". This TypeError doesn't occur each time the script is run.</p>
  
  <p>The flow is as follows:</p>
  
  <ol>
  <li>getName (randomly chooses a name from a list of names</li>
  <li>searchImage (uses the Bing search API to search photographs associated with that name</li>
  <li>processBotdata (takes the results from Bing and randomly chooses one of the search results)</li>
  </ol>
  
  <p>Step 3 is where the issue occurs:</p>
  
  <pre><code>function processBotdata (searchData, callback) {
  
      var photographer = searchData.photographer // the search name
      var array        = searchData.array; // search results from bing
      var randomIndex  = Math.floor(Math.random() * array.length);
      var mediaUrl     = array[randomIndex].MediaUrl; // TypeError here!
      var sourceUrl       = array[randomIndex].SourceUrl;
      var searchData         = {
                             photographer,
                             mediaUrl,
                             sourceUrl
                            };
      fs.readFile('results.json', function (err, data) {
      var json = JSON.parse(data);
      json.push(['search results for ' + photographer + ': ',
                                'mediaUrl: ' + searchData.mediaUrl,
                                'sourceUrl: ' + searchData.sourceUrl]);
  
      fs.writeFile("results.json", JSON.stringify(json, null, "\t"));
      console.log(' ==========&gt; searchData appended to results.json file...')
      });
      console.log(' ==========&gt; searchData has now been processed for upcoming tweet...');
      setTimeout(function() {
        callback(null, searchData);
        console.log(searchData);
      }, 5000);
  }
  </code></pre>
  
  <p>I implemented a <code>setTimeout</code> for this function hoping that would resolve the issue. My thinking was that the Bing results <code>searchData.array</code> was not yet available to be processed, i.e. randomized and selected in this function. As I am new to Node.js and JavaScript I am unsure of my programming error here. I saw this <a href="https://stackoverflow.com/questions/8023591/node-js-async-foreach-cannot-read-property-value-of-undefined">post</a> and I am wondering if it is related to the Bing Search Array which returns the top 50 results.</p>
  
  <p>Update: here is how the <code>async.waterfall</code> is called:</p>
  
  <pre><code>async.waterfall([
      getName,
      async.retryable([opts = {times: 5, interval: 500}], searchImage),
      async.retryable([opts = {times: 3, interval: 1000}], processBotdata),
      async.retryable([opts = {times: 3, interval: 500}], getImage)
  ],
  function(error, result) {
      if (error) {
        console.error(error);
        return;
        }
  });
  </code></pre>