I need to fetch all direct reports for the logged in manager and then display a card component for each one. I have to make a separate async call getPhoto(id)
for each report by iterating over the response array of employee objects.
The following is my original attempt, which after running eslint
, I realized is inefficient due to the sequential await
's inside the for...of
loop.
async function getReports() {
const response = await fetch('/current_user_direct_reports')
.then(res => res.json())
.then(data => data.value)
.catch(error => console.log(error));
for (const report of response) {
report.photo = await getPhoto(report.userPrincipalName);
}
setReports(response)
}
useEffect(() => {
getReports();
}, []);
This works but is rather slow. I tried adjusting the code to collect a list of employee objects, each containing a photo Promise
, in order to allow all requests to resolve simultaneously.
async function getReports() {
const response = await fetch('/current_user_direct_reports')
.then(res => res.json())
.then(data => data.value)
.catch(error => console.log(error));
const reportsAndPhotos = [];
for (const report of response) {
const emp = report;
emp.photo = getPhoto(report.userPrincipalName);
reportsAndPhotos.push(emp);
}
return (await Promise.all(reportsAndPhotos));
}
useEffect(() => {
async function getEmployees() {
const reportsAndPhotos = await getReports();
setReports(reportsAndPhotos);
setLoaded(true);
}
getEmployees();
}, []);
However, my response is repeatedly rendered empty and I cannot identify what I'm doing wrong. I thought Promise.all()
would wait for everything to resolve before returning.