Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda