Search code examples
dartdart-async

Dart nested futures whenComplete fires first


I need to make a series of database queries that each return a stream of results. Once all the information is collected and sent the 'complete' message needs to be send last. In my code 'sendCompleteMessageToClient' gets sent first.

 Future.forEach(centerLdapNames.values, (center) {
   db
       .collection(center)
       .find({'date': {'\$gte': json['from'], '\$lt': json['to']}})
       .forEach(sendAppointmentToClient);
 }).whenComplete(() => sendCompleteMessageToClient("all"));

How do I wait for all 'sendAppointmentToClient' to finish properly?


Solution

  • I guess you just miss the return of the future

    Future.forEach(centerLdapNames.values, (center) {
       return db // <== always return the returned future from calls to async functions to keep the chain connected
           .collection(center)
           .find({'date': {'\$gte': json['from'], '\$lt': json['to']}})
           .forEach(sendAppointmentToClient);
     }).whenComplete(() => sendCompleteMessageToClient("all"));
    

    If you use wait these calls might be executed in parallel instead of one after the other

    Future.wait(centerLdapNames.values.map((center) { ...}, eagerError: false)
    .whenComplete((...))