飞镖的完成和未来?

时间:2012-12-05 21:08:31

标签: 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;
  }

以上是从github SQLJocky Connector

获取的示例代码

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

简而言之,我无法理解打印执行后的部分。

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

我已经探索了以下链接: Google groups discussion on Future and Completer

和api参考文档,如下所示 Completer api referenceFuture api Reference

3 个答案:

答案 0 :(得分: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");
}

这是link to a blog post which details other scenarios where futures are helpful

答案 1 :(得分:1)

完成符用于为未来提供值,并指示它触发附加到未来的任何剩余回调和延续(即在呼叫站点/用户代码中)。

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

void complete(T value)

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

答案 2 :(得分:0)

正确答案在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");
}

reslut

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