0

I have a JS file with two methods that is used to take in an array of strings, make a fetch call to apis based on the string provided, create a JS object from the response, push the object into an array, and return the array of objects.

The issue comes when trying to validate the data inside of the array. When I try to interact with the JS objects inside of the array, it says that it is undefined. Before the push, it is considered an object and I can see the data accurately, but after the push it is undefined and I cannot access the data.

JS Code

export default function getFullResources(titles){
    let resources = [];

    titles.forEach(element => {
        titleAPICall(element)
        .then((item)=>{
            console.log(typeof item) //returns Object
            console.log(item) //returns an Object with the accurate data
            resources.push(item);
        })
    });
    console.log(resources) //returns an array of length 2 with the Objects and accurate data
    console.log(typeof resources[0]) //returns undefined
    console.log(typeof resources[1]) //returns undefined
    return resources
}

async function titleAPICall(title){
    var callURL = "" + title
    return fetch(callURL, {
        'method': 'GET'
    })
    .then((response)=>response.json())
    .then((txt)=>{ 
        return {
            title: String(txt.value[0].Title),
            shortsummary: String(txt.value[0].shortsummary),
            dateCreated: String(txt.value[0].DateCreated),
            URL: String("" + title),
        };  
    }); 
}

I am new to JS so apologies in advance if this is considered a 'simple' error, I have searched all over and have not been able to determine the issue.

  • `console.log(resources) ` onwards until the end of your function occurs before you `.push()` anything into your `resources` array, you'll need to deal with the `item` data inside of your `.then()` callback – Nick Parsons Feb 26 '20 at 06:02
  • @NickParsons I actually want to manipulate the `item` data inside of the JS function that makes the initial call. Is there a way to modify what I have now so that when the calling function receives the returned array, it can still manipulate the `item` data inside the array instead of it being undefined? – booftechie Feb 26 '20 at 06:33
  • if you manipulate the data in the `.then()` callback you'll be able to wrap your data in a Promise and `resolve()` with that data. However, I suggest you do it this way: https://jsfiddle.net/kyx0heg1/1/ using `Promise.all` – Nick Parsons Feb 26 '20 at 06:50
  • 1
    @NickParsons Woohoo!!! This is exactly what I needed! Thank you so much! :) – booftechie Feb 26 '20 at 07:00

0 Answers0