title: Refactoring code to move code inside function results in undefined error
body: <p>I'm trying to restructure some code. Right now it looks like this:</p>
  
  <pre><code>async function myfunction(ref) {
    var r1 = await getReport(ref, "queue", "hour", "2018-10-03", "2018-10-04", "pageviews", "page");
    var r2 = await getReport(r1.reportID, "get").then(r2 =&gt; reportHandler(r1.reportID, r2, 0));
    return r2;
  }
  
  const data= await myFunction(ref);
  if(data!=null &amp;&amp; data.report.data!=null){
    const result = data.report.data.reduce((r, e) =&gt; {
      e.breakdownTotal.forEach(el =&gt; {
        let key = "data";
        if(!r[key]) r[key] = []
        r[key].push(...el.counts)
      })
      return r;
    }, {})
  }
  </code></pre>
  
  <p>However, I want to restructure it to be in a single function like this:</p>
  
  <pre><code>async function myfunction(ref) {
    var r1 = await getReport(ref, "queue", "hour", "2018-10-03", "2018-10-04", "pageviews", "page");
    var r2 = await getReport(r1.reportID, "get").then(r2 =&gt; reportHandler(r1.reportID, r2, 0));
    if(r2!=null &amp;&amp; r2.report.data!=null) {
      const result = r2.report.data.reduce((r, e) =&gt; {
        e.breakdownTotal.forEach(el =&gt; {
          let key = "data";
          if(!r[key]) r[key] = []
          r[key].push(...el.counts)
        })
        return r;
      }, {})
    }
  }
  </code></pre>
  
  <p>However I've not had any luck getting this to work. In this particular case I get this error:</p>
  
  <blockquote>
    <p>mytest3.html:10 Uncaught (in promise) TypeError: Cannot read property
    'data' of undefined
        at myfunction (mytest3.html:10)</p>
  </blockquote>
  
  <p>Reporthandler code:</p>
  
  <pre><code>async function reportHandler(id, r2, retries) {
    if (retries &gt;= 3 || r2.error != "report_not_ready") return r2;
    await sleep(2000);
    var report = await getReport(id, "get");
    return reportHandler(id, report, retries + 1);
  }
  </code></pre>