如何在 Dart 的循环中完全同步调用异步 API?
How to call an async API fully synchronously within a loop in Dart?
如何在 Dart 的循环中完全同步地调用异步 API?
例如,如果我有
for(...) {
await doSomethingLongAsync();
}
据我了解,doSomethingLongAsync() 将在循环的每次迭代中按顺序但异步地调用,即循环的每次后续迭代甚至在前一次迭代的调用完成之前都会异步调用 doSomethingLongAsync()。
我需要确保循环的后续迭代不会调用 doSomethingLongAsync(),直到前一次迭代对同一函数的调用完全完成。
as I understand, doSomethingLongAsync() will be invoked sequentionally but asynchronously on each iteration of the loop, i.e. each subsequent iteration of the loop will asynchronously call doSomethingLongAsync() even before the call of the previous iteration completes.
这是不正确的,当您 await
时,它将不会继续(在 async
函数的上下文中),直到正在等待的 Future
完成。
What I need is to make sure that a subsequent iteration of the loop does not invoke doSomethingLongAsync() until the previous iteration's invokation of the same function fully completes.
您编写的代码已经做到了这一点。
为了说明,请尝试 运行 此代码:
Future<void> main() async {
for (int i = 0; i < 10; i++) {
print('start loop $i');
await doSomethingLongAsync(i);
print('end loop $i\n');
}
}
Future<void> doSomethingLongAsync(int i) async {
print('start doSomethingLongAsync $i');
await Future.delayed(const Duration(seconds: 2));
print('end doSomethingLongAsync $i');
}
您会看到它不会继续循环的下一次迭代,直到等待的 Future
完成。
如何在 Dart 的循环中完全同步地调用异步 API?
例如,如果我有
for(...) {
await doSomethingLongAsync();
}
据我了解,doSomethingLongAsync() 将在循环的每次迭代中按顺序但异步地调用,即循环的每次后续迭代甚至在前一次迭代的调用完成之前都会异步调用 doSomethingLongAsync()。
我需要确保循环的后续迭代不会调用 doSomethingLongAsync(),直到前一次迭代对同一函数的调用完全完成。
as I understand, doSomethingLongAsync() will be invoked sequentionally but asynchronously on each iteration of the loop, i.e. each subsequent iteration of the loop will asynchronously call doSomethingLongAsync() even before the call of the previous iteration completes.
这是不正确的,当您 await
时,它将不会继续(在 async
函数的上下文中),直到正在等待的 Future
完成。
What I need is to make sure that a subsequent iteration of the loop does not invoke doSomethingLongAsync() until the previous iteration's invokation of the same function fully completes.
您编写的代码已经做到了这一点。
为了说明,请尝试 运行 此代码:
Future<void> main() async {
for (int i = 0; i < 10; i++) {
print('start loop $i');
await doSomethingLongAsync(i);
print('end loop $i\n');
}
}
Future<void> doSomethingLongAsync(int i) async {
print('start doSomethingLongAsync $i');
await Future.delayed(const Duration(seconds: 2));
print('end doSomethingLongAsync $i');
}
您会看到它不会继续循环的下一次迭代,直到等待的 Future
完成。