sqljocky同步查询数据库

sqljocky同步查询数据库

问题描述:

我试图与sqljocky同步查询MySQL数据库。我有一个 Load 类运行查询并获取数据,然后将数据导入到 User 对象。我遇到的问题是未来,运行查询不能及时返回对象到调用方法。

I am trying to query a MySQL database synchronously with sqljocky. I have a Load class that runs the query and gets the data then imports the data into a User object. The problem I am having is the Future that runs the query is not returning in time to return the object to the calling method.

DataObject user = new DataObject();
user.Get(1234);
// I cannot do anything here because the returned object is null
user.somethingElse();

DataObject Get(String ID){
  return access.Load(this, ID);
}

// Runs query
Load(DataObject object, String ID){
  // Set up query
  String query = 'select * from users where ID = \'' + ID + '\'';
  // Run query
  var completer = new Completer.sync();
  pool.query(query).then((result) {
    result.listen((row) {
      // Import into object
      object.Import(row);
    }, onDone: () {
      completer.complete(object);
    });
  });
}


做这样的事情(注意未经测试的代码):

My guess is you want to do something like this (Note untested code):

Future<DBObject> load(DBObject object, String id) {
   var query = "select ... where id='$id'"; // Note: check for SQL injection.
   return pool.query(query)
    .then((result) => result.toList())
    .then((list) => list.forEach((row) => object.import(row)))
    .then((_) => object);
}

您已阅读此关于使用Futures的文章

关键是如果方法是异步的,调用代码需要等待它完成,然后它必须返回一个Future对象(或在某些情况下,Stream)。 Dart没有办法得到一个函数来阻塞等待异步结果。请随意在评论中提出更多问题。

The key point is if a method is asynchronous, and the calling code needs to wait for it to complete, then it must return a Future object (or a Stream in some cases). There is no way in Dart to get a function to "block" waiting for an asynchronous result. Feel free to ask some more questions in the comments.