1

in my code, there are functions which do async operations. so I have marked these called functions as async in the function body, I am using await for all the async operations. Is there any clear way to do that?

For example, I want to wrap all async operations with only one await keyword:

    Future<void> _clearTables()async{
      await{
        dbHelper.deleteDailyQuestions();
        dbHelper.deletePureCards();
        dbHelper.deleteStudiedCards();
      }
    }
aligur
  • 3,387
  • 3
  • 34
  • 51
  • You either can use [`Future.forEach`](https://api.dart.dev/stable/dart-async/Future/forEach.html) if you want to wait for each `Future` in succession, or you can use [`Future.wait`](https://api.dart.dev/stable/dart-async/Future/wait.html) if you want to wait for all of them concurrently. Also see: https://stackoverflow.com/a/63719805/ – jamesdlin Apr 26 '21 at 07:02
  • I was exactly looking for this kind of await block. – Eren Dec 24 '21 at 01:35

2 Answers2

1

Maybe you should try to use RxDart operators like swicthMap or concatMap? It makes a lot of sense in front end development. You can learn it here or here. Depending of when you want to get value you should use proper operator. You can decide to get value if each of the function have finished or take the result from the fastest only. A lot of options here. My suggestion is to find your question related to JavaScript code and then reuse it in Dart.

Ensei Tankado
  • 270
  • 2
  • 12
-1

You can add await for all the future returning functions

    Future<void> _clearTables()async{
      await dbHelper.deleteDailyQuestions();
      await dbHelper.deletePureCards();
      await dbHelper.deleteStudiedCards();
    }
Jay Dangar
  • 3,271
  • 1
  • 16
  • 35
  • This would run the functions one at a time, I'm assuming the author is looking for a way to run them in parallel. – Incinerator Aug 31 '22 at 12:20