Home > Enterprise >  Getting 400 error code when I run axios get request?
Getting 400 error code when I run axios get request?

Time:02-05

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?

CodePudding user response:

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.

CodePudding user response:

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);
    }
};
  •  Tags:  
  • Related