The ability for PHP programs to execute asynchronous functions… Yeah, I said it and now it exists. By coding in Facebook’s new Hack Language, using your CPU’s cycles correctly has never been so easy. Let’s delve into this new language head first!
|
|
As can be see, this function is no different than any normal PHP function. The only thing you have to notice is the function join()
called on line 14. This function calls the data from the asynchronous function initialized on line 7.
|
|
Note the async attribute of the function. This lets the compiler know the function is an asynchronous function. Secondly note the Awaitable return type. This will allow the function to use the await
reserved word.
The ‘await’ token tells the function that everything preceding runs asynchronously but has to wait for $info to be completed before continuing.
|
|
This function just sets a random time for calculations
to be completed to simulate work that could be done. The reason this function exists is to save the start and end times of the function.
The last thing that must be noted about these function is the WaitHandle. This allows async function to call other functions asynchronously.
Below is the final output. The last 5 lines say it all!
[main] Calling Async Function
[getInfo] Generating 0
[getInfo] Generating 1
[getInfo] Generating 2
[getInfo] Generating 3
[getInfo] Generating 4
[getInfo] Now Awaiting
[main] Triangulating Atlantis
[main] Calculating the Meaning Of Life
[main] Triangulating Atlantis
[main] Time To Request Async Return Information
[getInfo] Completed 2
[getInfo] Completed 0
[getInfo] Completed 4
[getInfo] Completed 1
[getInfo] Completed 3
[0] => {"id":0,"start":"22:20:34","end":"22:20:36"}
[1] => {"id":1,"start":"22:20:34","end":"22:20:37"}
[2] => {"id":2,"start":"22:20:34","end":"22:20:35"}
[3] => {"id":3,"start":"22:20:34","end":"22:20:39"}
[4] => {"id":4,"start":"22:20:34","end":"22:20:36"}
All said and done, this is the feature that made me want to start using Hack as a production language. Even if this language crashes and burns, like too many in the past, this feature alone allows me to be hopeful for the future.
Github: https://github.com/kernelcurry/hack-examples/blob/master/async.php