等待未来完成 [英] Wait for future to complete

查看:90
本文介绍了等待未来完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用postgres数据库查询来确定下一步操作。在执行下一行代码之前,我需要等待结果。现在,我的 conn.query 返回一个Future,但是当我将代码放在另一个函数中时,我无法使其异步。

I use my postgres database query to determine my next action. And I need to wait for the results before I can execute the next line of code. Now my conn.query returns a Future but I can't manage to get it async when I place my code in another function.

main() {
  // get the database connection string from the settings.ini in the project root folder 
  db = getdb();
  geturl().then((String url) => print(url));
}

Future geturl() {
  connect(db).then((conn) {
    conn.query("select trim(url) from crawler.crawls where content IS NULL").toList()
      .then((result) { return result[0].toString(); })
      .catchError((err) => print('Query error: $err'))
      .whenComplete(() {
        conn.close();
      });
  });
}

我只想要 geturl()等待返回的值,但是无论我做什么;它会立即射击。谁能指出我在其中解释我所缺少的文档的一部分?

I just want geturl() to wait for the returned value but whatever I do; it fires immediately. Can anyone point me a of a piece of the docs that explains what I am missing here?

推荐答案

您实际上并没有返回当前 geturl 中的Future。您必须实际返回使用的期货:

You're not actually returning a Future in geturl currently. You have to actually return the Futures that you use:

Future geturl() {
  return connect(db).then((conn) {
    return conn.query("select trim(url) from crawler.crawls where content IS NULL").toList()
      .then((result) { return result[0].toString(); })
      .catchError((err) => print('Query error: $err'))
      .whenComplete(() {
        conn.close();
      });
  });
}

这篇关于等待未来完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆