飞镖的完成和未来?

IBR*_*RIT 7 dart dart-async

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;
  }
Run Code Online (Sandbox Code Playgroud)

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

我想有人解释我如果可能的话,为什么是具有之外,那么pool.query被调用函数completer.complete(空)创建的完成者对象的功能.

总之,我无法理解打印执行后的部分.

注意:如果可能的话,我也想知道未来和Completer如何用于DB和非DB操作的实际用途.

我已经探讨了以下链接: Google对Future和Completer的讨论

和api参考文档,如下面的 完整api参考Future api参考

Joh*_*ans 9

在某种意义上,该方法返回的Future对象连接到该完成对象,该对象将在"将来"的某个时刻完成.在Completer上调用.complete()方法,它表示未来它已完成.这是一个更简化的例子:

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

main(){
   someFutureResult().then((String result) => print('$result'));
   print("you should see me first");
}
Run Code Online (Sandbox Code Playgroud)

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

  • @JohnEvans 博客文章页面链接已损坏。 (2认同)

chu*_*han 6

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

\n\n
error : The argument type \'int\' can\'t be assigned to the parameter type \'Duration\'.\nerror : The argument type \'(dynamic) \xe2\x86\x92 void\' can\'t be assigned to the parameter type \'() \xe2\x86\x92 void\'.\n
Run Code Online (Sandbox Code Playgroud)\n\n

以下片段是补充

\n\n
import \'dart:async\';\n\nFuture<dynamic> someFutureResult(){\n   final c = new Completer();\n   // complete will be called in 3 seconds by the timer.\n   new Timer(Duration(seconds: 3), () {     \n       print("Yeah, this line is printed after 3 seconds");\n       c.complete("you should see me final");       \n   });\n   return c.future;\n\n}\n\nmain(){\n   someFutureResult().then((dynamic result) => print(\'$result\'));\n   print("you should see me first");\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

结果

\n\n
you should see me first\nYeah, this line is printed after 3 seconds\nyou should see me final\n
Run Code Online (Sandbox Code Playgroud)\n