0

I have some code which seems to work just fine:

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 => reportHandler(r1.reportID, r2, 0));
  console.log(r2);
}

The console.log(r2); outputs this result:

{report: {…}, waitSeconds: 0, runSeconds: 0}
report:
data: Array(4)
0:
breakdown: [{…}]
breakdownTotal: ["608674"]
day: 1
month: 10
name: "Mon.  1 Oct. 2018"
year: 2018
__proto__: Object
1:
breakdown: [{…}]
breakdownTotal: ["564566"]
day: 2
month: 10
name: "Tue.  2 Oct. 2018"
year: 2018

I'm trying to output the value of 'breakdownTotal' using code I have built using online tutorials

const result = data.report.data.reduce((r, e) => {
  e.breakdownTotal.forEach(el => {
    let key = "data";
    if(!r[key]) r[key] = []
    r[key].push(...el.counts)
  })
  return r;
}, {})

However, I get this error:

Uncaught (in promise) ReferenceError: data is not defined
    at myfunction (mytest3.html:12)
8
  • You wan the breakdownTotal as output right? r2.breakdownTotal isn't working? Commented Oct 10, 2018 at 10:23
  • There is no JSON here, JSON is a string notation, your just dealing with javascript objects, they're not the same thing Commented Oct 10, 2018 at 10:24
  • what's data here? how and where do you call this function? Commented Oct 10, 2018 at 10:25
  • @Liam data i thought was the structure of the object/json Commented Oct 10, 2018 at 10:26
  • ?? I'm not sure what your trying to say. You have no variable called data so it's obviously undefined. There is no magic data variable Commented Oct 10, 2018 at 10:27

1 Answer 1

2

Return r2 from myFunction

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 =>    reportHandler(r1.reportID, r2, 0));
  return r2;
}

Create data from myFunction(ref);

const data= await myFunction(ref);
if(data!=null && data.report.data!=null){
const result = data.report.data.reduce((r, e) => {
  e.breakdownTotal.forEach(el => {
  let key = "data";
   if(!r[key]) r[key] = []
    r[key].push(...el.counts)
  })
  return r;
  }, {})
}
Sign up to request clarification or add additional context in comments.

6 Comments

This is also screaming out for some null checking. if data, report or report.data are null it'll break
So he can put the code of const result with in if statment that check data and data.report.data
also const data= await myFunction(ref);
It will be best
@Osama It tells me Uncaught SyntaxError: await is only valid in async function
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.