Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Not able to aggregate data returned from the twilio api

I'm trying to fetch the billing data from the Twilio API and save the returned value in a variable so that I can return it and display it in my web app. I know it's related to async, I tried using async and await but wasn't able to make it work.

const twilio = require("twilio");

client = twilio(
  "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "AUTHXXXXXXXXXXXXXXXXXXXXXXXXXXX"
);

const filterOpts = {
  startDate: "2021-08-01",
  endDate: "2021-08-31",
};

let result = []
function getBillingData() {
  client.usage.records.each(filterOpts, async (record) => {
    let temp = await record;
    result.push(temp);
  });
}


getBillingData();
console.log(result.length);

When I try to run this, it prints 0

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

const filterOpts = {
  startDate: "2021-08-02",
  endDate: "2021-08-02",
  callback: (data) => {result.push(data);} ,
  done: () => {console.log(result.length);},
};


async function getBillingData() {
  client.usage.records.each(filterOpts);
}

async function getData() {
  await getBillingData();
};

getData();

I went through the documentation to find the that I can pass two optional parameters which would do my work.

about 4 years ago · Juan Pablo Isaza Report

0

Twilio developer evangelist here.

I think this issue is a race condition with asynchronous calls in your JS and you code returning before the asynchronous calls are finished. I think the each call is asynchronous too. Try this:


async function getBillingData() {
  let result = []
  await client.usage.records.each(filterOpts, async (record) => {
    let temp = await record;
    result.push(temp);
  });
  return result;
}


getBillingData().then((result) => {
  console.log(result.length);
})

Now the getBillingData function is an async function, so it can use await on the call to client.usage.records.each. It also collects the results within itself and returns the value when the function resolves.

Finally, we use getBillingData().then() to ensure that the data is collected and returned before logging it.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!