Home > Article > Backend Development > PHP async
Async here stands for Asynchronous, which means the process is not synchronous. Asynchronous allows the parallel execution of the code. That means we can run the piece of code separately and independently of each other. This is generally called the async process, and this is the same in PHP. We have the Async model in PHP, which allows us to have multi-task execution simultaneously. It makes the execution of the code faster and increases the performance as well.
ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
In PHP, we can use the Spatie package to use the async feature. With this package, we can create a pool that will handle our async call and help us provide the parallel execution of the program. For better understating, we can have a look at the syntax. See below;
//package to be used use Spatie\Async\Pool; $mypool = Pool::create(); $mypool[] = async() { //your logic goes here })->then() { // your logic });
First, we need to import the package, which is ‘SpatieAsyncPool’ here. After that, we are creating a pool that will handle the async operations for us. Followed by ‘async’ keyword inside this, we will write our whole logic and piece of code that we want to run in parallel. Here we have a ‘then’ method, which is a callback method. Inside this, we can also write our own logic. After all the operations, we can write more operations on the given output in the ‘then’ block.
Now we know that the async function allows us the execution of multiple tasks. If we talk about Synchronous programming in PHP, so we will always have output in the same order. suppose we want to print the number from 1 to 10. So if I write this logic using the Synchronous code, I will always get it in ascending order. But if we try to use the async code here for the same logic, then we are not sure about the order of number. We will discuss this in more detail with some examples below. To write the async code in PHP, we have used one package called ‘spatie’. This also provides us with better handling of errors and exceptions in async code. First, we will see how to write a simple logic using this package. Then we will discuss the more methods that can be used with async code in detail later on.
Example:
use Spatie\Async
cmd:
composer require spatie
Example:
$mypool = Pool::create();
We can give any name to the pool object. also, do not forget to import the Pool class present inside ‘Async’. See below;
Example:
use Spatie\Async\Pool;
Example:
demoAsync(function () { // // }) ->then(function ($output) { // // })
In the above piece of code, we are creating an async function and using its callback method ‘then.’ This ‘then’ function is responsible for operating when the above code block is executed successfully. If not, then we need to handle that case by using other methods of Async.
Now we will see some methods to handle the error, exceptions, and timeouts that can occur while executing the code. This package provides us with various methods to handle this inside the async block of the code. Let’s discuss each of them in detail. See below;
The method will be executed when the block of code fails to perform its operations within the expected timeframe or encounters an error. The following is the syntax to write this method:
Example:
timeout(function () { // when timeout reached. })
The method will be executed if the block of code is executed successfully and there is a need to perform additional operations on the result. The following is the syntax to write this method:
Example:
then(function ($result) { // operation after result })
This method will be executed if the block of code throws an exception. Inside this method, we can handle them and perform our logic. The syntax to write this method is shown below;
Example:
catch(function ($exp) { // exception can be handle here. })
Following are the examples given below:
In this example, we are implementing async with the method and printing two messages to keep it simple for beginners.
Code:
use Spatie\Async\Pool; $mypool = Pool::create(); $mypool ->asyncDemo(function () { print("async called here !!") }) ->then(function () { print("then called after result !!") } ;
Output:
In this example, we are using all the methods of async from the Spatie\Async\ package. Those are catch, then, and timeout. We keep it simple for now without too much logic.
Code:
use Spatie\Async\Pool; $mypool = Pool::create(); $mypool ->asyncDemo(function () { print("async called here !!") print("async called here !!") }) ->then(function ($output) { print("print called here !!") }) ->catch(function ($exception) { print("catch called here !!") }) ->timeout(function () { print("timeout called here !!") }) ;
Output:
By using async in our code, we can enable parallel execution of tasks in our program. Also, they increase the performance of the code because the piece of code is independent of each other. But using StopIteration in situations where the data from the previous block of code is dependent on the current can lead to data loss and inconsistency.
The above is the detailed content of PHP async. For more information, please follow other related articles on the PHP Chinese website!