那个
"START----END"
打印“无序”是期货的一种行为,一开始大多数开发人员都会感到困惑。
像这样的电话
connection.query()
返回未来的命令不立即执行,而是登记在队列中以供稍后执行。当前执行线程将继续执行,直到完成,然后一个接一个地处理队列。
在代码中不起作用的是您执行异步调用
connection.query()
然后继续,就像它是一个同步呼叫一样。这在达特是行不通的。当您开始异步执行时,无法返回同步。(据我所知,计划的异步/等待应该可以解决这个问题)。
更多详情请访问dartlang.org
The Event Loop and Dart
EDIT测试代码
import 'dart:io';
import 'package:sqljocky/sqljocky.dart';
final connection = new ConnectionPool(host: 'localhost', port: 3306, user: 'root', password: null, db: 'server1');
main() {
HttpServer.bind(InternetAddress.ANY_IP_V4, 9090)..then((server) {
print("serving generic database query on localhost:9090");
server.listen((request) {
if (request.method == "GET") {
getResults()
.then((result) {
print('Result: $result');
request.response.write(result);
request.response.close();
});
}
else {
request.response.statusCode = HttpStatus.BAD_REQUEST;
}
});
});
}
Future<String> getResults() {
StringBuffer sb = new StringBuffer();
sb.write("START--");
return connection.query("select name, email, zkey from users")
.then((Result results) => results.toList())
.then((list) {
list.forEach((row) {
sb.write(row.toString());
});
sb.write("--END");
})
.then((_) => sb.toString());
}
另请参阅Gregs关于如何读取SqlJocky结果的回答
sqljocky querying database synchronously