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
JavaScript
x
23
23
1
List: [
2
{ tick: "AAPL", datePurch: "01/01/2021"},
3
{ tick: "GOOG", datePurch: "01/01/2021"},
4
{ tick: "TSLA", datePurch: "01/01/2021"},
5
{ tick: "J", datePurch: "01/01/2021"},
6
{ tick: "AMZN", datePurch: "01/01/2021"},
7
{ tick: "FB", datePurch: "01/01/2021"},
8
{ tick: "BABA", datePurch: "01/01/2021"},
9
{ tick: "JNJ", datePurch: "01/01/2021"},
10
{ tick: "JPM", datePurch: "01/01/2021"},
11
{ tick: "XOM", datePurch: "01/01/2021"},
12
],
13
14
totalPortfolio(){
15
const arr = List.map((i) => (
16
fetch(`${IEX.base_url}/stock/${i.tick}/intraday-prices?chartLast=1&token=${IEX.api_token}`)
17
.then(response => response.json())
18
.then(arr => arr.push(arr))
19
));
20
console.log(arr);
21
}
22
23
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()
:
JavaScript
1
24
24
1
const List = [
2
{ tick: "AAPL", datePurch: "01/01/2021" },
3
{ tick: "GOOG", datePurch: "01/01/2021" },
4
{ tick: "TSLA", datePurch: "01/01/2021" },
5
{ tick: "J", datePurch: "01/01/2021" },
6
{ tick: "AMZN", datePurch: "01/01/2021" },
7
{ tick: "FB", datePurch: "01/01/2021" },
8
{ tick: "BABA", datePurch: "01/01/2021" },
9
{ tick: "JNJ", datePurch: "01/01/2021" },
10
{ tick: "JPM", datePurch: "01/01/2021" },
11
{ tick: "XOM", datePurch: "01/01/2021" },
12
];
13
14
async function getIntradayPrice(tick) {
15
const resp = await fetch(`${IEX.base_url}/stock/${tick}/intraday-prices?chartLast=1&token=${IEX.api_token}`);
16
return resp.json();
17
}
18
19
async function totalPortfolio() {
20
const respPromises = List.map(({ tick }) => getIntradayPrice(tick));
21
const respArrays = await Promise.all(respPromises);
22
console.log(respArrays);
23
}
24