0

In the code below I'm saving the data I get from a stock API to newData and then I want to pass this newData to data which is supposed to be a global variable as an array. The main goal is to then save this array as CSV, but I first need to get the array

const yahooStockAPI  = require('yahoo-stock-api');

let data = [];

async function main() {
    const startDate = new Date('07/01/2021');
    const endDate = new Date('07/25/2021');
    const newData = await yahooStockAPI.getHistoricalPrices(startDate, endDate, 'AAPL', '1d');
    data = newData

};
console.log(data);

When I print data, I get back [ ] an empty array. Shouldn't it retrieve the data from the API instead? I've searched other questions like this in stackoverflow and tried to implement some of the fixes, but none seem to be working

For reference, this is the ouput I get from the await yahooStockAPI.getHistoricalPrices(startDate, endDate, 'AAPL', '1d'); line of code

{
  error: false,
  currency: 'USD',
  response: [
    {
      date: 1627047000,
      open: 147.5500030517578,
      high: 148.72000122070312,
      low: 146.9199981689453,
      close: 148.55999755859375,
      volume: 71447400,
      adjclose: 148.33775329589844
    },
    {
      date: 1626960600,
      open: 145.94000244140625,
      high: 148.1999969482422,
      low: 145.80999755859375,
      close: 146.8000030517578,
      volume: 77338200,
      adjclose: 146.58038330078125
    },...

This is the data I want to save in the global variable data array

Thank you in advance

user139442
  • 91
  • 1
  • 11

1 Answers1

1

The problem is your main function is never called, so there will never be stored a value in your data variable, you need to explicitly call your main function

I assume you mix some things up with c/c++?

const yahooStockAPI  = require('yahoo-stock-api');

let data = [];

async function main() {
    const startDate = new Date('07/01/2021');
    const endDate = new Date('07/25/2021');
    const newData = await yahooStockAPI.getHistoricalPrices(startDate, endDate, 'AAPL', '1d');
    data = newData

};

// call your main function
await main();

console.log(data);

Edit after comment from @evolutionxbox

Using top-level await will only work inside modules and should only be used in certain situations

Here are some resources you can take a look at:

sschwei1
  • 362
  • 2
  • 11
  • 1
    https://stackoverflow.com/questions/46515764/how-can-i-use-async-await-at-the-top-level please note that using await at the top level is only allowed in certain places – evolutionxbox Aug 09 '21 at 11:10
  • 1
    @evolutionxbox Thanks a lot, I just tried it in a playground and it worked, I didn't even know this was a thing, gonna read a bit into it and update my answer – sschwei1 Aug 09 '21 at 11:15