Skip to content
Advertisement

How to populate array with values from API using “fetch” in javascript function

I’m trying to write a function that builds an array where each value of the array is a value pulled from an API using a unique url, once the value is fetched from the API it is pushed into the existing array.

Basically when the function is called I want to populate an array with fetched API data for each stock ticker listed in the List, what i have so far doesnt seem to be working though

List: [
                { tick: "AAPL", datePurch: "01/01/2021"},
                { tick: "GOOG", datePurch: "01/01/2021"},
                { tick: "TSLA", datePurch: "01/01/2021"},
                { tick: "J", datePurch: "01/01/2021"},
                { tick: "AMZN", datePurch: "01/01/2021"},
                { tick: "FB", datePurch: "01/01/2021"},
                { tick: "BABA", datePurch: "01/01/2021"},
                { tick: "JNJ", datePurch: "01/01/2021"},
                { tick: "JPM", datePurch: "01/01/2021"},
                { tick: "XOM", datePurch: "01/01/2021"},
                ],

 totalPortfolio(){
        const arr = List.map((i) => (
            fetch(`${IEX.base_url}/stock/${i.tick}/intraday-prices?chartLast=1&token=${IEX.api_token}`)
                .then(response => response.json())
                .then(arr => arr.push(arr))
            ));
        console.log(arr);
    }
  

Advertisement

Answer

You’ll need to await for all of the fetches to finish before you log things.

Reworking your code to async/await functions and adding the required Promise.all():

const List = [
  { tick: "AAPL", datePurch: "01/01/2021" },
  { tick: "GOOG", datePurch: "01/01/2021" },
  { tick: "TSLA", datePurch: "01/01/2021" },
  { tick: "J", datePurch: "01/01/2021" },
  { tick: "AMZN", datePurch: "01/01/2021" },
  { tick: "FB", datePurch: "01/01/2021" },
  { tick: "BABA", datePurch: "01/01/2021" },
  { tick: "JNJ", datePurch: "01/01/2021" },
  { tick: "JPM", datePurch: "01/01/2021" },
  { tick: "XOM", datePurch: "01/01/2021" },
];

async function getIntradayPrice(tick) {
  const resp = await fetch(`${IEX.base_url}/stock/${tick}/intraday-prices?chartLast=1&token=${IEX.api_token}`);
  return resp.json();
}

async function totalPortfolio() {
  const respPromises = List.map(({ tick }) => getIntradayPrice(tick));
  const respArrays = await Promise.all(respPromises);
  console.log(respArrays);
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement