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

134
Vistas
Getting 400 error code when I run axios get request?

I write some code to getting info

const stock = await Stock.find({
    exchange: exchange
});
// Here stock array length is 5300

stock.forEach(async (stockEl) => {
    const EOD_API = process.env.EOD_HISTORICAL_API
    const {data} = await axios.get(`https://eodhistoricaldata.com/api/fundamentals/${stockEl.code}?api_token=${EOD_API}&filter=General::Industry`);
    console.log(data);
});

Here I place get request for every stock array element by forEach function. Then it give me error like image- Click to see images

But When I place it outside of forEach function like this-

const EOD_API = process.env.EOD_HISTORICAL_API
const {data} = await axios.get(`https://eodhistoricaldata.com/api/fundamentals/${stockEl.code}?api_token=${EOD_API}&filter=General::Industry`);
console.log(data);

Then it gives no error. For Remembering Stock has 5300 element, that means axios run 5300 times.

Any solution or idea?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Doing await in forEach doesn't hold the process since forEach is not promise-aware. Try this instead:

(async () => {
    for (let index = 0; index < stock.length; index++) {
        const EOD_API = process.env.EOD_HISTORICAL_API
        const {data} = await axios.get(`https://eodhistoricaldata.com/api/fundamentals/${stock[i].code}?api_token=${EOD_API}&filter=General::Industry`);
        console.log(data);
    }
})();

More information.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to make a few changes:

  • Replace forEach with for because forEach is not promise aware

  • Use try, catch => catch any errors

  • Use Promise.allSettled => it allows you to run all promisses together without waiting each other which in return will enhance your app performance. It returns an array with status ("fulfilled", "rejected")

    const fetchSingleStockElement = async (stockEl) => {
          try {
              const EOD_API = process.env.EOD_HISTORICAL_API,
                  { data } = await axios(
    
    `https://eodhistoricaldata.com/api/fundamentals/${stockEl.code}?api_token=${EOD_API}&filter=General::Industry`
                  );
              return data;
          } catch (err) {
              throw new Error(err);
          }
      };
    
      const fetchAllStockData = async () => {
          let promisesArray = [];
          try {
              //fetch stock array
              const { data } = await Stock.find({
                  exchange: exchange
              });
    
              //fetch single stock
              for (let i = 0; i < data.length; i++) {
                  promisesArray.push(fetchSingleStockElement(data[i].id));
              }
    
              const results = await Promise.allSettled(promisesArray);
              console.log('results', results);
          } catch (err) {
              console.log('results error', err);
          }
    

    };

Here is a working example with fake API of 4466 entries:

const fetchSingleAirline = async (airlineId) => {
        try {
            const { data } = await axios(`https://api.instantwebtools.net/v1/airlines/${airlineId}`);
            return data;
        } catch (err) {
            throw new Error(err);
        }
    };

const fetchAllAirlineData = async () => {
    let promisesArray = [];
    try {
        const { data } = await axios('https://api.instantwebtools.net/v1/airlines');
        for (let i = 0; i < data.length; i++) {
            promisesArray.push(fetchSingleAirline(data[i].id));
        }

        const results = await Promise.allSettled(promisesArray);
        console.log('results', results);
    } catch (err) {
        console.log('results error', err);
    }
};
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