the_iceman
the_iceman

Reputation: 45

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

Upvotes: 0

Views: 69

Answers (2)

the_iceman
the_iceman

Reputation: 45

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.

Upvotes: 1

philnash
philnash

Reputation: 73055

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.

Upvotes: 0

Related Questions