Dart avait Future,推迟特定行代码并执行其余代码
Dart avait Future, postpone just certain line of code and execute the rest
想要推迟某些代码行,为此使用 await Future 并且效果很好,问题是它推迟了它之后的所有代码,我需要它在继续执行 rest 的同时推迟某些代码行立即输入代码
void main() async {
for (int i = 0; i < 5; i++) {
await Future.delayed(Duration(seconds: 1));
//postpone just next line or few lines of code
print('postpone this line of code ${i + 1}');
print('postpone me too');
}
//should execute without being postponed
print('continue imediately without being postponed by await Future');
}
这可以用 await Future 或其他函数实现吗?
await
它是注册 Future.then
回调的语法糖。使用 await
的目的是让所有后续代码更容易等待 Future
完成。如果那不是你想要的,你可以直接使用Future.then
:
void main() {
for (int i = 0; i < 5; i++) {
Future.delayed(const Duration(seconds: 1)).then((_) {
print('postpone this line of code ${i + 1}');
print('postpone me too');
});
}
print('continue immediately without being postponed by await Future');
}
由于Future.delayed
需要回调,你也可以完全跳过then
:
void main() {
for (int i = 0; i < 5; i++) {
Future.delayed(const Duration(seconds: 1), () {
print('postpone this line of code ${i + 1}');
print('postpone me too');
});
}
print('continue immediately without being postponed by await Future');
}
如果你不使用创建的未来,这相当于使用 Timer
:
import 'dart:async' show Timer;
void main() {
for (int i = 0; i < 5; i++) {
Timer(const Duration(seconds: 1), () {
print('postpone this line of code ${i + 1}');
print('postpone me too');
});
}
print('continue immediately without being postponed by await Future');
}
想要推迟某些代码行,为此使用 await Future 并且效果很好,问题是它推迟了它之后的所有代码,我需要它在继续执行 rest 的同时推迟某些代码行立即输入代码
void main() async {
for (int i = 0; i < 5; i++) {
await Future.delayed(Duration(seconds: 1));
//postpone just next line or few lines of code
print('postpone this line of code ${i + 1}');
print('postpone me too');
}
//should execute without being postponed
print('continue imediately without being postponed by await Future');
}
这可以用 await Future 或其他函数实现吗?
await
它是注册 Future.then
回调的语法糖。使用 await
的目的是让所有后续代码更容易等待 Future
完成。如果那不是你想要的,你可以直接使用Future.then
:
void main() {
for (int i = 0; i < 5; i++) {
Future.delayed(const Duration(seconds: 1)).then((_) {
print('postpone this line of code ${i + 1}');
print('postpone me too');
});
}
print('continue immediately without being postponed by await Future');
}
由于Future.delayed
需要回调,你也可以完全跳过then
:
void main() {
for (int i = 0; i < 5; i++) {
Future.delayed(const Duration(seconds: 1), () {
print('postpone this line of code ${i + 1}');
print('postpone me too');
});
}
print('continue immediately without being postponed by await Future');
}
如果你不使用创建的未来,这相当于使用 Timer
:
import 'dart:async' show Timer;
void main() {
for (int i = 0; i < 5; i++) {
Timer(const Duration(seconds: 1), () {
print('postpone this line of code ${i + 1}');
print('postpone me too');
});
}
print('continue immediately without being postponed by await Future');
}