在继续执行其余代码之前,我需要我的异步函数等待某些表达式进行验证(例如 x == true)。
现在我正在使用 while 循环
var x = false;
someFunction() async {
// here I want to await for
// as long as it takes for x to become true
while(!x) {
await new Future.delayed(new Duration(milliseconds: 250));
}
// i put 250 millisecond intentional delay
// to protect process from blocking.
// x is to be set true by external function
// rest of code ...
}
await someFunction();
Run Code Online (Sandbox Code Playgroud)
您认为在继续执行之前等待 x 变为真有更好的方法吗?谢谢
你可以做这样的事情。
Future<void> _waitUntilDone() async {
final completer = Completer();
if (_loading) {
await 200.milliseconds.delay();
return _waitUntilDone();
} else {
completer.complete();
}
return completer.future;
}
Run Code Online (Sandbox Code Playgroud)
甚至更好
var completer;
Future<void> _waitUntilDone() async {
completer = Completer();
return completer.complete();
}
void done() {
if (completer)
completer.complete();
}
Run Code Online (Sandbox Code Playgroud)
在完全调用时,我们也可以发出一些值。
Doc*_*Doc -1
像这样的东西吗?
delayed() async {
await Future.delayed(Duration(seconds: 2));// or some time consuming call
return true;
}
somefn() async{
var x = await delayed();
print(x);// gives true
}
somefn();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5450 次 |
| 最近记录: |