Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
How to make my code dry in JavaScript during API Call

SO I am calling 5 APIs in my js file and the code is the same for all except the URL and the form data I am passing. and same lines of code repeats 5 times and I think this is not the good of writing. What I want is to make this code dry but don't know what changes I should make

var formdata = new FormData();
        formdata.append("market", "KSE100");

        var requestOptions = {
            method: "POST",
            body: formdata,
            redirect: "follow",
        };

        fetch(
            "api_url here_1",
            requestOptions
        )
        .then((response) => response.json())
        .then((stockData) => console.log('aasfs',stockData ))
        .catch((error) => console.log("error", error));



var formdata = new FormData();
            formdata.append("symbol", "SYS");
    
            var requestOptions = {
                method: "POST",
                body: formdata,
                redirect: "follow",
            };
    
            fetch(
                "api_url here_2",
                requestOptions
            )
            .then((response) => response.json())
            .then((stockData) => console.log('aasfs',stockData ))
            .catch((error) => console.log("error", error));
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can define a function like this

const postData = (url, data) => {
        const formdata = new FormData();
        Object.entries(data).forEach(([k, v]) => {
          formdata.append(k, v);
        }
        

        var requestOptions = {
            method: "POST",
            body: formdata,
            redirect: "follow",
        };

        return fetch(
            url,
            requestOptions
        )
        .then((response) => response.json())
        .then((stockData) => console.log('aasfs',stockData ))
        .catch((error) => console.log("error", error));

}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Wrap the common code in a function passing in the form data and url via variables

const sendFormData = (url, formData) => {
  var requestOptions = {
    method: "POST",
    body: formData,
    redirect: "follow",
  };

  fetch(
      url,
      requestOptions
    )
    .then((response) => response.json())
    .then((stockData) => console.log('aasfs', stockData))
    .catch((error) => console.log("error", error));
}

var formdata1 = new FormData();
formdata.append("market", "KSE100");
sendFormData("api_url here_1", formdata1);

var formdata2 = new FormData();
formdata.append("symbol", "SYS");
sendFormData("api_url here_2", formdata2);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda