-1

Here is a summary of what I'm trying to do:

  1. Make a call to an AOU using the accountId - this returns an array of items.
  2. I need to use the item.ReportDate to make another call to the AOU to get projects.
  3. I map the ReportDates to a variable
  4. I set a new empty array variable named projects
  5. Loop through ReportDates.Items and push the items into projects
  6. Now when I console.log projects, it shows a list of projects however if I try to access them individually like projects[0], it gives back undefined. I am assuming this is due to it being async.

How can I access the resolved projects?

Here is a shortened version of what the data calls look like:

// First api call to retrieve ReportDates:

fetch(baseUrl + "api/Woh/Summary/" + accountId): 
AccountId.Items: [
   {
    AccountId: 124,
    clientName: XYZ,
    reportDate: "2018-09-30"
   },
   {
    AccountId: 124,
    clientName: XYZ,
    reportDate: "2018-09-20"
   },
]

// Next using a loop to make fetch calls using reportDates:

fetch(baseUrl + "api/Woh/Details/" + accountId + "/" + reportDate)
reportDate.Items(first loop): 
[
 {a:y}, 
 {b:z},
 {c:v}
]

reportDate.Items(second loop): 
[
 {a:y}, 
 {b:z}
]

Now I'm trying to push all the items in each call to compile it all into 1 array. And that's where I'm having trouble accessing after the loop is complete.

Here is my code:

const getProjectsData = async () => {
    let projectsData = await fetch(baseUrl + "api/Woh/Summary/" + accountId);
    let projectsJson = await projectsData.json();
    let reportDates = projectsJson.Items.map(item => formatDate(item.ReportDate));
    let projects = [];
    reportDates.forEach(reportDate => {
        fetch(baseUrl + "api/Woh/Details/" + accountId + "/" + reportDate)
            .then(res => res.json())
            .then(data => {
                data.Items.forEach(item => projects.push(item));
            })
    });
    console.log(dates);
    // console logging dates shows the array of items that I want, but when I try to access them individually with dates[0], it shows as undefined. 
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Scott Au
  • 1
  • 2
  • 1
    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) – jonrsharpe Dec 27 '19 at 17:16

1 Answers1

0

If you use async/await, you won't have to think too hard about loops. You can loop through with a for- block, like so:

async function getResults(objs) {
    const responses = [];
    for (let obj of objs) {
        const response = await fetch(`/data/${obj.id}`);
        const json = await response.json();
        responses.push(json);
    }
    return responses;
}

getResults([{id:1},{id:2}])
TKoL
  • 13,158
  • 3
  • 39
  • 73
  • Hey thanks for the answer. This is really close! Except I need to do one more step after the first loop, so it actually looks more like this: async function getResults(objs) { const responses = []; for (let obj of objs) { const response = await fetch(`/data/${obj.id}`); const json = await response.json(); json.Items.forEach(item => responses.push(item)); } console.log(responses); return responses; } -the console log shows the correct array, but the return shows undefined – Scott Au Dec 27 '19 at 19:17
  • 1
    an async function returns implicitly a Promise so get your data with `getResults().then(res=>console.log(res))` – fubar Dec 28 '19 at 13:39
  • @ScottAu fubar is correct, async functions return promises. You can await it, `const results = await getResult()`, or use the `.then` callback – TKoL Dec 28 '19 at 18:49