【问题标题】:The inside of the loop is asynchronous, how to synchronize the outside [duplicate]循环内部是异步的,外部如何同步[重复]
【发布时间】:2021-12-08 19:42:47
【问题描述】:

例如:

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);
  });
}

将输出:

gogo 结束 主端 1 2 3 4

我期待的结果:

1 2 3 4 gogo结束 主端

【问题讨论】:

  • 使用for (var element in list) {...,而不是list.forEach((element) ...
  • 我改成void gogo(List list) async { // list.forEach((element) async { // await pS(element); // }); for(String element in list){ await pS(element); } print('gogo end'); }但是不行
  • 你也需要await gogo(list);await Future.delayed
  • 知道了,谢谢!

标签: flutter


【解决方案1】:

这是您所期望的,我也在示例中进行了说明。

// 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);
  });
}

【讨论】:

  • ty,我将await Future.wait([ for (var element in list) pS(element), ]); 更改为for (var element in list) await pS(element); 然后得到相同的结果
  • 您可以这样做,但所有pS 函数将一个一个运行,而不是同时运行。例如:不是运行“等待 1 秒 -> 同时打印 1 2 3 4”,而是运行“等待 1 秒 -> 打印 1 -> 等待 1 秒 -> 打印 2 -> 等待 1 秒 -> 打印” 3 ...."
猜你喜欢
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2018-10-17
  • 2017-04-07
  • 2021-12-12
  • 2012-09-10
  • 1970-01-01
  • 2018-06-17
相关资源
最近更新 更多