1

for example:

void main() {
  List<String> list = ['1', '2', '3', '4'];
  gogo(list);
  print('main end');
}

void gogo(List list) async {
  list.forEach((element) async {
    await pS(element);
  });

  print('gogo end');
}

Future pS(String s) async {
  Future.delayed(Duration(seconds: 1), () {
    print(s);
  });
}

will output:

gogo end main end 1 2 3 4

The result I am looking forward to:

1 2 3 4 gogo end main end

Zhuoyuan.Li
  • 318
  • 2
  • 10

1 Answers1

1

Here is what you expect, I also explained in the example.

// Create an async main method to work with Future
void main() async {
  List<String> list = ['1', '2', '3', '4'];
  await gogo(list);
  print('main end');
}

Future gogo(List list) async {
  // Use this method if you want to run all functions at the same time
  // and wait until all functions are completed
  //
  // You can't use List.foreach() because it is not a Future function
  // so you have no way to await it
  await Future.wait([
    for (var element in list) pS(element),
  ]);

  print('gogo end');
}

Future pS(String s) async {
  // You also need to await this function
  await Future.delayed(Duration(seconds: 1), () {
    print(s);
  });
}
Lam Thanh Nhan
  • 486
  • 4
  • 5
  • 1
    ty, and I changed `await Future.wait([ for (var element in list) pS(element), ]);` to `for (var element in list) await pS(element);` then get the same result – Zhuoyuan.Li Oct 22 '21 at 06:35
  • 2
    You can do it but all `pS` functions will run one by one, not at the same time. Ex: Instead of run "wait 1 second -> print 1 2 3 4 at the same time" it will run like "wait 1 second -> print 1 -> wait 1 second -> print 2 -> wait 1 second -> print 3 ...." – Lam Thanh Nhan Oct 22 '21 at 06:39