Dartlang wait more than one future

后端 未结 2 729
忘掉有多难
忘掉有多难 2020-12-02 18:25

I want to do something after a lot of future function done,bu I do not know how to write the code in dart? the code like this:

for (var d in data) {
  d.load         


        
相关标签:
2条回答
  • 2020-12-02 18:54

    Existing answer gives enough information, but I want to add a note/warning. As stated in the docs:

    The value of the returned future will be a list of all the values that were produced in the order that the futures are provided by iterating futures.

    So, that means that the example below will return 4 as the first element (index 0), and 2 as the second element (index 1).

    import 'dart:async';
    
    Future main() async {
      print('start');
    
      List<int> li = await Future.wait<int>([
        fetchLong(),  // longer (which gives 4) is first
        fetchShort(), // shorter (which gives 2) is second
      ]);
    
      print('results: ${li[0]} ${li[1]}'); // results: 4 2
    }
    
    Future<int> fetchShort() {
      return Future.delayed(Duration(seconds: 4), () {
        print('Short!');
        return 2;
      });
    }
    
    Future<int> fetchLong() {
      return Future.delayed(Duration(seconds: 5), () {
        print('Long!');
        return 4;
      });
    }
    
    0 讨论(0)
  • You can use Future.wait to wait for a list of futures:

    import 'dart:async';
    
    Future main() async {
      var data = [];
      var futures = <Future>[];
      for (var d in data) {
        futures.add(d.loadData());
      }
      await Future.wait(futures);
    }
    

    DartPad example

    0 讨论(0)
提交回复
热议问题