Search code examples
postgresqldartdart-async

how to get data from conn.query in dart


I am doing dart with postgresql , I can't return data the conn.query(rows). but the results are coming ,how to return it, simple code is

    main(){
     someOtherFunc();
    }
   Future add() async{
   var uri = 'postgres://postgres:root@localhost:5432/testdb';
   var conn = await connect(uri);
   var sql = 'select * from test';
   return conn.query(sql).toList();
 }


 Future someOtherFunc() async {
   print(await add());
 }

I got return as "Instance of '_Future'!"


Solution

  • If you use await in the function you call add() from, you get the desired result

    Future add() async {
      var uri = 'postgres://postgres:root@localhost:5432/testdb';
      var conn = await connect(uri);
      var sql = 'select * from test';
      return conn.query(sql).toList();
    }
    
    Future someOtherFunc() async {
      print(await add());
    }
    

    async is contagious. When you call an async function, you can't return to sync execution. Everything that depends on the async results, needs to use await (or the "old" .then((value) {})) . async + await just create the illusion of sync execution.