Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Dart have sync APIs?

I am thinking about using Dart for server side programming. Because are no full frameworks similar to Ruby on Rails, I am reviewing lower level libraries. The most needed library is Posgresql driver. I found few and most mature seems to be https://pub.dartlang.org/packages/postgresql

And here is my problem. The Postgresql driver has async API. I know that async APIs are required for client side, simply to not block UI thread. However on server side threads are available so why Postgresql driver has async API?

I known about Promises APIs but for me this is just unneeded complexity when doing things on server side. Code readability is most important.

I just wonder if there is something in Dart language design that forces people to build async APIs. So the question is: can Dart have sync APIs for database and file IO operations?

like image 233
Greg Dan Avatar asked Dec 01 '25 07:12

Greg Dan


1 Answers

Dart libraries/packages can offer sync APIs. DB ones don't tend to, because you usually don't want to block the entire server waiting for a potentially long DB operation to finish. For example, say you're creating a web server, with a request handler that fetches data from the DB and serves it. If you're only using sync operations, and you get 10 requests, 9 of those will be waiting for the first one to finish before being processed.

If your only concern is readability, you can wait for the await keyword to be implemented, which will help your code feel like sync code, while actually working async:

var conn = await connect(uri);
var results = await conn.query('select * from users').toList();
for(result in results) {
    print("${result.username} has email address ${result.emailAddress}.");
}
like image 132
Tonio Avatar answered Dec 03 '25 23:12

Tonio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!