In the following code block, I am trying to set an array as the value for a local variable by calling a function that returns an array. The issue arises because the Promises in the second function are not resolved until after the array has been returned to the caller. I have attempted using Promise.all() on retArray without success. Upon running console.log() on my someobject object, the arrOfTitles field does not print out because the call to SkywalkerTitles() results in an empty array.
You can try out the code here.
Now the question is, how can I get someObject.arrOfTitles to retrieve the array of titles from SkywalkerTitles()?
function SkywalkerTitles(){
let retArray = [];
fetch('https://swapi.co/api/people/')
.then(function(response){
response.json()
.then(function(result){
return result.results[0];
})
.then(function(result){
result.films.forEach(function(film){
fetch(film)
.then(function(response){
response.json().then(function(result){
console.log(result.title);
retArray.push(result.title);
});
});
})
.catch(function(error){
console.log(error)
});
});
})
.catch(function(error){
console.log(error)
});
}
function UseReturnedArray() {
let someObject = { aThing: '', anotherThing: '', arrOfTitles: null };
someObject.aThing = 'Thing One';
someObject.anotherThing = 'Thing Two';
someObject.arrOfTitles = SkywalkerTitles();
console.log('Object With Returned Array:\n\n', JSON.stringify(someObject, null, 2));
}
UseReturnedArray();