Reputation: 55
I have a collection named sessions, inside each session there is a coach id which is a document id for a user document. I'm trying to read all sessions and then for each session I want to fetch the user document, the coaches list (users) leaves the bloc empty, I figured it's an issue with asynchronous tasks.
List<Session> sessions;
List<MyUser> coaches;
yield AdminsessionsLoading();
await datasource
.fetchMonthSessions(event.month, event.year)
.then((data) async => {
sessions = data,
data.forEach((session) async => {
await adminDatasource
.fetchUser(session.coachId)
.then((coach) => coaches.add(coach))
})
});
//after fetching sessiosn, fetch the coaches
print(coaches);
print("Sessions Fetched " +
" - Sessions : " +
sessions.length.toString() +
" - Coaches : " +
coaches.length.toString());
yield AdminsessionsLoaded(sessions: sessions, coaches: coaches);
}
What is the correct way for me to read coaches and sessions the right way ?
Upvotes: 0
Views: 48
Reputation: 3499
.forEach()
has no return value, and you cannot await it - so while your code spawns multiple asynchronous tasks, it doesn't wait for any of them. You could use
await Promise.all(
data.map((session) async => {
await adminDatasource
.fetchUser(session.coachId)
.then((coach) => coaches.add(coach))
})
});
);
to wait for all of them to complete ( .map()
will return an array of promises). This is a HUGE limitation of .forEach()
in asynchronous code.
Upvotes: 1