Hacklang异步代码示例?

时间:2014-11-16 09:53:12

标签: asynchronous hhvm hacklang

如何修改以下代码以在hack中异步获取文章数据和热门文章?

class ArticleController
{
    public function viewAction()
    {
        // how get
        $article = $this->getArticleData();
        $topArticles = $this->getTopArticles();
    }

    private function getArticleData() : array
    {
        // return article data from db
    }

    private function getTopArticles() : array
    {
        // return top articles from db
    }
}

2 个答案:

答案 0 :(得分:3)

警告from the async documentation page与此相关:

  

目前基本支持异步。例如,你可以   目前编写调用其他异步函数的基本异步函数。   但是,我们目前正在最终确定其他基础(例如异步   数据库,调度和内存处理API)这将是必需的   在生产中充分发挥异步的潜力。但我们觉得,   介绍异步的概念和技术会很有用   (即使有基本功能),以便让开发人员习惯   语法和一些技术细节。

因此,遗憾的是,您实际使用异步函数所需的原始数据库查询尚不可用。上面链接的文档讲述了异步函数的一般工作原理,并包含了一个合并读取的示例,您现在可以使用异步函数执行此操作。

数据库API最终即将推出,但尚未推出,抱歉!

答案 1 :(得分:2)

HHVM 3.6及更新版

async函数信息

  

启用异步功能的两个HHVM PHP语言关键字是asyncawaitasync将函数声明为异步。 await暂停执行async函数,直到await表示的异步操作的结果可用。可以使用await的函数的返回值是实现Awaitable<T>的对象。

您在文档(1)中有一个示例。在语言规范中也讨论了异步函数(2)

我花了一些时间才意识到如何使用和调用异步函数,所以我认为你会发现一些更有用的信息。

我们有以下两个功能:foo()bar()

async function foo(): Awaitable<void> {
  print "executed from foo";
}
async function bar(int $n): Awaitable<int> {
  print "executed from bar";
  return $n+1;
}

让我们尝试一些方法来调用这两个函数:

foo();                  // will print "executed from foo"
bar(15);                // will print "executed from bar"
$no1 = bar(15);         // will print "executed from bar"
print $no1;             // will output error, because $number is not currently an `int`; it is a `WaitHandle`
$no2 = bar(15)->join(); // will print "executed from bar"
print $no2;             // will print 16

AsyncMysqlClient提示

使用AsyncMysqlClient::connect异步函数与MySQL数据库建立连接,该函数将ExternalThreadEventWaitHandle返回AsyncMysqlConnection

您可以AsyncMysqlConnection执行queryqueryf注意:您发送给queryf的数据已被该功能正确转义。

您在AsyncMysqlConnection上执行的查询会返回AsyncMysqlQueryResult(查询执行正常时)或AsyncMysqlQueryErrorResult(如果查询出错;那么您可以使用{处理错误此类的{1}},mysql_error()mysql_errno()成员。 failureType()AsyncMysqlQueryResult都扩展了AsyncMysqlResult个抽象类。

以下是您班级的可能实施方式:

AsyncMysqlQueryErrorResult

P.S。我希望这个答案还为时不晚,我希望它可以帮到你。如果您认为这很有用,请接受它。

相关问题