如何修改下面的代码以异步获取文章数据和顶级文章?
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
}
}发布于 2015-08-20 08:01:37
HHVM 3.6及更高版本
async函数信息
启用异步函数的两个HHVM语言关键字是
async和await。async将函数声明为异步函数。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 16AsyncMysqlClient提示
与MySQL数据库的连接使用AsyncMysqlClient::connect异步函数进行,该函数将ExternalThreadEventWaitHandle返回给AsyncMysqlConnection。
您可以在query或queryf上执行AsyncMysqlConnection。注意:函数正确地转义了发送给queryf的数据。
在AsyncMysqlConnection上执行的查询返回AsyncMysqlQueryResult (当查询执行ok时)或AsyncMysqlQueryErrorResult (如果查询出错,则可以使用该类的mysql_error()、mysql_errno()和failureType()成员处理错误)。AsyncMysqlQueryResult和AsyncMysqlQueryErrorResult都扩展了AsyncMysqlResult抽象类。
以下是您的类的可能实现:
class ArticleController {
private AsyncMysqlConnection $connection;
public async function viewAction(int $articleId): Awaitable<void> {
$this->connection = await AsyncMysqlClient::connect( /* connection data */ );
$article = await $this->getArticleData($articleId);
}
public async function getArticleData(int $id): Awaitable<?Vector> {
$articleDataQuery = await $this->connection->queryf("SELECT * FROM articles WHERE id %=d", $id);
if($articleDataQuery instanceof AsyncMysqlQueryErrorResult) {
throw new Exception("Error on getting data: ".$articleDataQuery->mysql_error());
}
// Considering that $id represents a unique id in your database, then
// you are going to get only one row from your database query
// so you return the first (and only) row in the query result
if($articleDataQuery->numRows() == 1) {
return $articleDataQuery->mapRowsTyped()[0];
}
return null;
}
} P.S.我希望这个答案不会太晚,我希望它能对你有所帮助。如果你认为这有用,请接受它。
发布于 2014-11-16 20:24:41
警告从异步文档页面在这里是相关的:
目前有对异步的基本支持。例如,您目前可以编写调用其他异步函数的基本异步函数。然而,我们目前正在最后确定其他基础(例如异步数据库、调度和内存处理API),这将是实现异步在生产中的全部潜力所必需的。不过,我们认为引入异步(即使具有基本功能)的概念和技术是有用的,以便让开发人员习惯于语法和一些技术细节。
因此,不幸的是,实际使用异步函数所需的原始数据库查询还不可用。上面链接的文档讨论了异步函数一般是如何工作的,并包括一个合并抓取的示例,您现在可以使用异步函数来完成这一工作。
DB最终要来了,但是现在还没有,对不起!
https://stackoverflow.com/questions/26955694
复制相似问题