function only returns predises

Asked

Viewed 49 times

-1

I’m studying on JS with Node and Express. I am developing an application that will consult emergency relief data through the GOV API.

I have a function that returns the JSON data of a given CPF, it works normal if passed only 1 CPF.
When I try to call this dare function from another function, it only returns an error due to the await.

Function that queries in the api:

async function getConsultaBeneficiario(data) {
  var obj = [];
  try {
    var url = `http://www.transparencia.gov.br/api-de-dados/auxilio-emergencial-por-cpf-ou-nis?codigoBeneficiario=${data.cpf}&pagina=1`;
    var opt = {
      headers: {
        'chave-api-dados': 'minhaChave'
      },
    };

    const response = await axios.get(url, opt);
    if (response.data == '' || response.data == null) {
      obj = {
        cpf: `${data.cpf}`,
        nome: `${data.nome}`,
        Message: 'sem informação',
      };

      return obj;

    }

    obj = response.data;
    return obj;
  } catch (error) {
    console.log(
      'Error - erro na consulta do CPF - function getConsultaBeneficiario(cpf)'
    );
    console.log(error);
  }
}

In this function I call the function above, passing through loop, several cpfs for query:

async function getListaBeneficioJson() {
  var listaBenef = [];
  var jsonBenef = `${__dirname}/json/file.json`;
  var data = [];
  try {
    var benef = JSON.parse(fs.readFileSync(jsonBenef, 'utf-8'));

    var resut = benef.map((item) => {
      console.log('chamando funcao getConsultaBeneficiario'); 
      data.push(await getConsultaBeneficiario(item)); // erro se da por essa linha
    });
  } catch (error) {
    console.log(error);
  }

  return listaBenef;
}

1 answer

0


SOLUTION:

const getListaBeneficioJson = async () => {
  var listaBenef = [];
  var jsonBenef = `${__dirname}/json/file.json`;
  try {
    var benef = JSON.parse(fs.readFileSync(jsonBenef, 'utf-8'));

    benef = benef.map(async (user) => {
      const datas = await getConsultaBeneficiario(user);
      // console.log(datas);
      return datas;
    });

    listaBenef = (async () => {
      listaBenef = await Promise.all(benef);
      // console.log(listaBenef);
      //console.log('fim da lista');
      return listaBenef;
    })();

    return listaBenef;
  } catch (error) {
    console.log(error);
  }
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.