dart 的完成者和未来?

问题描述 投票:0回答:3
Future readData() {
    var completer = new Completer();
    print("querying");
    pool.query('select p.id, p.name, p.age, t.name, t.species '
        'from people p '
        'left join pets t on t.owner_id = p.id').then((result) {
      print("got results");
      for (var row in result) {
        if (row[3] == null) {
          print("ID: ${row[0]}, Name: ${row[1]}, Age: ${row[2]}, No Pets");
        } else {
          print("ID: ${row[0]}, Name: ${row[1]}, Age: ${row[2]}, Pet Name: ${row[3]},     Pet Species ${row[4]}");
        }
      }
      completer.complete(null);
    });
    return completer.future;
  }

以上是取自github的示例代码SQLJocky Connector

如果可能的话,我希望有人解释一下为什么在 pool.query 之外创建了一个完成者对象的函数然后调用一个函数completer.complete(null)。

总之我无法理解 print 执行后的部分。

注意:如果可能的话,我还想知道 future 和 Completer 如何用于数据库和非数据库操作的实际目的。

我探索了以下链接: Google 就 Future 和 Completer 进行小组讨论

以及 api 参考文档,如下所示 完整 api 参考未来 api 参考

dart dart-async
3个回答
32
投票

该方法返回的 Future 对象在某种意义上连接到该完成者对象,该对象将在“未来”的某个时刻完成。 .complete() 方法在 Completer 上调用,这向未来发出它已完成的信号。这是一个更简化的示例:

Future<String> someFutureResult(){
   final c = Completer();
   // complete will be called in 3 seconds by the timer.
   Timer(3000, (_) => c.complete("you should see me second"));
   return c.future;
}

main(){
   final result = someFutureResult().then((String result) => print(result);
   print("you should see me first");
}

这是一篇博客文章的链接,其中详细介绍了期货有用的其他场景


6
投票

DartPad 中正确答案有错误,原因可能是 Dart 版本。

error : The argument type 'int' can't be assigned to the parameter type 'Duration'.
error : The argument type '(dynamic) → void' can't be assigned to the parameter type '() → void'.

以下片段是补充

import 'dart:async';

Future<dynamic> someFutureResult(){
   final c = new Completer();
   // complete will be called in 3 seconds by the timer.
   new Timer(Duration(seconds: 3), () {     
       print("Yeah, this line is printed after 3 seconds");
       c.complete("you should see me final");       
   });
   return c.future;

}

main(){
   someFutureResult().then((dynamic result) => print('$result'));
   print("you should see me first");
}

结果

you should see me first
Yeah, this line is printed after 3 seconds
you should see me final

3
投票

Completer 用于向 future 提供一个值,并指示它触发附加到 future 的任何剩余回调和延续(即在调用站点/用户代码中)。

completer.complete(null)
用于向未来发出异步操作已完成的信号。完整的 API 显示它必须提供 1 个参数(即不是可选的)。

void complete(T value)

此代码对返回值不感兴趣,只是通知调用站点操作已完成。由于它只是打印,您需要检查控制台的输出。

© www.soinside.com 2019 - 2024. All rights reserved.