0

Can you help me?

I did a fetch API and now a I want to make a module.export to use the variable named pricesInfoRoot in other archive js.

The console says that the variable is undefined, I already tried to use more promises due the response of the API but didn't work.

Here it is the code:

require("isomorphic-fetch");

require("../config/authorization.js")

let baseURL = require("../baseURL/baseURL");
const authorization = require("../config/authorization.js");

let body = {
  app_key: authorization.app_key,
  app_secret: authorization.app_secret,
  call: "ListarProdutos",
  param: [
    {
        "pagina": 1,
        "registros_por_pagina": 50,
        "apenas_importado_api": "N",
        "filtrar_apenas_omiepdv": "N"
    },
  ],
};

let pricesInfoRoot;

async function priceConsult() {
  let request = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  };

  try {
    let apiResponse = await fetch(`${baseURL}/geral/produtos/`, request);

    if (apiResponse.status == 200) {
      let finalResponse = await apiResponse.json();

        return priceTreat(finalResponse);

    } else {
      throw Error("Error searching products");
    }
  } catch (error) {
    console.log(error);
  }

}

priceConsult().then(result => {
    pricesInfoRoot = result;
});


let priceTreat = (priceProducts) => {

    return priceProducts.produto_servico_cadastro.map(price => {
      return {
        PartNumber: price.codigo,
        Preço: price.valor_unitario,
      };
    });

};
module.exports = pricesInfoRoot```
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Your promise callback hasn't run by the time you reach `module.exports = ...` because it is asynchronous. However, even if you fix that problem, you can't do this. `module.exports` has to be resolved synchronously. Typically you would export a function that would return an asynchronous result. – user229044 Feb 11 '23 at 19:42

0 Answers0