How modify the following code to get article data and top articles asynchronously in 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
}
}
HHVM 3.6 and newer
async
functions infoYou have an example in the documentation (1). There is a discussion about asynchronous functions in the language specification as well (2).
It actually took me some time to realize how to use and call the asynchronous functions, so I think you will find some more info useful.
We have these two functions:
foo()
andbar()
.Let's experiment some ways to call these two functions:
AsyncMysqlClient
tipsThe connection to a MySQL database is made with
AsyncMysqlClient::connect
asynchronous function which returns anExternalThreadEventWaitHandle
to anAsyncMysqlConnection
.You can perform
query
orqueryf
on anAsyncMysqlConnection
. Note: the data you send to aqueryf
is properly escaped by the function.A query you perform on an
AsyncMysqlConnection
returns either anAsyncMysqlQueryResult
(when the query performs ok) orAsyncMysqlQueryErrorResult
(if the query goes wrong; then you can treat errors with themysql_error()
,mysql_errno()
andfailureType()
members of this class). BothAsyncMysqlQueryResult
andAsyncMysqlQueryErrorResult
extendAsyncMysqlResult
abstract class.Below is a probable implementation of your class:
P.S. I hope it is not too late for this answer and I hope it helps you. If you consider this useful, please, accept it.