1

I am building an application to collate all the indicators that I use while investing in the stock market, as a personal project. I am currently making use of the yahoo-finance API. Given below is my code for one of the data loading functions, that will later be used with Tulind package.

var yahooFinance = require("yahoo-finance");
var returnValue = [];

const loadData = (symbol, from, to, freq) => {
    let open = [];
    let close = [];
    let high = [];
    let low = [];
    let volume = [];
    let updateValues = () => {
        returnValue.map((e) => {
            open.push(e.open);
            close.push(e.adjClose);
            high.push(e.high);
            low.push(e.low);
            volume.push(e.volume);
        });
    };

    const data = yahooFinance.historical(
        {
            symbol: symbol,
            from: from,
            to: to,
            freq: freq,
        },
        function (error, quotes) {
            if (error)
                console.log("Error in server/indicatorCalc/parent_calc.js", err);
            else {
                returnValue = quotes;
            }
            console.log("Data loaded in parent_calc.js");
        }
    );
    updateValues();
    return {
        open,
        close,
        high,
        low,
        volume,
    };
};
// console.log(tulind.indicators);

module.exports = { loadData };

Given above is the function, which has an API endpoint at localhost:5000/indicatorParent/
For testing purposes, the API is being called using the thunderclient extension on VSCode.
The first request sent with the required parameters is outputting an empty value (or the previous value if this is not the first request). When I click the send button for the second time, it gets updated with the correct/expected values. I want to know how to rectify this apparent "lag" in the updating of the returnValue variable.
I am open to suggestions in changes in the flow of code as well.

Fauzaan
  • 13
  • 3
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – derpirscher Nov 22 '22 at 07:03
  • Furthermore, don't use `map` to iterate over a collection, but a loop or `forEach` – derpirscher Nov 22 '22 at 07:05
  • @derpirscher Thanks for the suggestion on the usage of forEach. I tried to look into the link you sent on async calls. I tried to convert the data variable into a function, and passed in a callback as suggested in the link you sent. But it seems to return an empty value. What would you edit in my code to help me go about this issue? – Fauzaan Nov 22 '22 at 07:42

0 Answers0