I'm using 2 api calls (one has employee name, id ..etc., the other api has employee social media links) to fetch employee data.
- employees API
{
persons:[
{ name: "Jane" },
{ name: "Joe" },
{ name: "Jim" }
]
}
- Social Media API
{
name: "Joe",
url: "http://fb.com/joeCool"
}
So I'd have to do a social-media-api call for every employee and save that data to an array:
[
{name: "Jane", url: "http://instagram.com/janeIsBest"},
{name: "Joe", url: "http://fb.com/joeCool"},
{name: "Jim", url: "http://snapchat.com/jimBo"}
]
The problem is with nested fetch calls. I can output the variable (api response is assigned to this variable) and it shows all the employee info, but when I console.log(employee.url) it shows undefined.
javascript looks like so
async function loadFullEmployeeInfo() {
const employeesSocialMediaPath = 'https://somewhere.io/api/socialmedia/';
const employeesApi = 'https://somewhere.io/api/employees';
const response = await fetch(employeesApi)
.then(response => response.json())
.then(data => data.persons)
.then(persons => {
persons.map(async (person) => {
person.url = await fetch(`${employeesSocialMediaPath}${employee.id}`).then(response => response.json()).then(data => data.url)
})
return persons;
})
.catch((error) => {console.log(`Error: ${error}`)})
console.log(response);
return response;
}
and data is saved like so:
const employeesInfo = await loadFullEmployeeInfo();
employeesInfo is referenced later on, when I do console.log(employeesInfo), it shows everything, including the url, but when I do console.log(employeesInfo.url) it shows undefined. Any explanation (especially ELI5) appreciated
Edit Figured it out, in addition to having to return Promises.all(response), I had the wrong array.map syntax
I should've done this
const response = await fetch(employeesApi)
.then(response => response.json())
.then(data => data.persons)
.then(persons => {
const nPersons = persons.map(async (person) => {
await fetch(`${employeesSocialMediaPath}${employee.id}`)
.then(response => response.json())
.then(data => {person.url = data.url;})
return person;
})
return nPersons;
})
.catch((error) => {console.log(`Error: ${error}`)});
return Promise.all(response);