How to make async functions in PHP ?
Last Updated :
06 Oct, 2022
In this article, we'll learn about the async function in PHP.
Let us understand what is the meaning of Async (Asynchronous):
A program does not need to be executed line by line. The program calls the function and moves further (does not wait for the function to return). It will execute in the background. Non-Blocking methods are executed asynchronously. Async allows the parallel execution of the code. Async is also used to make faster execution of code and allow us the execution of multiple task.
Async Function in PHP:
- In synchronous programming, if we want to read some file and return its content other functions block until the current function returns.
- But an asynchronous programming program calls the function and moves further and all the same is happening in the background.
- To write the Async program in PHP, we need to libraries (ReactPHP and Amp) which is used to implement non-blocking I/O in php.
- AMP is a concurrency framework for php and allows us to manage event loops, async iterators, and promises.
Before going to the code, let's first understand the functions provided by AMP:
1. then() Function: The then() function is executed only when the block of code in Async is successfully executed and we can perform operations on the result returned by Async.
Syntax:
then(function () {
// You can write operations here..
})
2. timeout() Function: The timeout() function occurs when the php request takes longer time than usual and it does not need a parameter.
Syntax:
timeout(function () {
// Execute when request takes longer time to execute.
})
3. catch Block: Exceptions are handled in the catch. When the program throws an exception(error) catch block will be executed.
Syntax:
catch(function ($exception) {
// Here we can handle exceptions
})
4. await() Function: The await function allows us to wait until async returns.
Syntax:
await($promise);
5. Promise: A promise represents a single result of an asynchronous operation.
$promise = $deferred->promise();
The steps required for "Async Code" are given below:
Step 1: You have to install composer to import libraries(ReactPHP and Amp).
Step 2: Initialize the composer using the following command.
composer init
Step 3: Create .php file. Your Project Structure should look like this.
Step 4: To implement the Async function we need to import the package first by using composer.
composer require amphp/react-adapter
Step 5: Import class present inside AMP.
PHP
<?php
$loop = Amp\ReactAdapter\ReactAdapter::get();
?>
Note: If you get an error like this "Uncaught Error: Class "Amp\ReactAdapter\ReactAdapter" not found in C:". Include this inside your PHP code: require __DIR__ . '/vendor/autoload.php';
Let us take a few examples to understand this concept better:
Example 1: In asynchronous programming, the program calls the function and moves further and allows the execution of multiple tasks. For eg: If we first write the table of 2 and then we write some print functions, then the print function will execute first due to non-blocking I/O.
PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<?php
require 'vendor/autoload.php';
$loop = Amp\ReactAdapter\ReactAdapter::get();
$loop ->addtimer(1, function(){
foreach (range(1, 5) as $i) {
$output = $i * 2;
echo " ", $output . "<br>". " ";
}
echo " After Table". "<br>". " ";
});
echo " After Loop Time". "<br>". " ";
$loop->run();
?>
</body>
</html>
Output:
Example 2: Reading text file using Async. We can read a file in a non-blocking asynchronous way, where the program calls the function and move to another function, does not wait for the function to return. When the file is completely read then it is printed.
PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<?php
require 'vendor/autoload.php';
$loop = Amp\ReactAdapter\ReactAdapter::get();
$loop ->addtimer(1, function(){
$file = fopen("amar.txt", "r");
while(!feof($file)) {
echo fgets($file). "<br>". " ";
}
echo " After Reading File ". "<br>". " ";
});
echo " After Loop Time". "<br>". " ";
$loop->run();
?>
</body>
</html>
Output:
Similar Reads
How to Type an Async Function in TypeScript ? An asynchronous function allows your code to do multiple things at once. It doesn't block the execution of the rest of your code while waiting for a long task (like reading a file, making an API request) to finish. Instead, it returns a Promise, making it easier to handle operations that might take
3 min read
How to chain asynchronous functions in JavaScript ? JavaScript is a single-threaded, asynchronous programming language. Thus, some time-consuming operations like I/O, accessing the database, network calls, etc. are performed asynchronously so that it does not interrupt things in the only JS thread. This can be done by asynchronous code like promises
2 min read
PHP fdatasync() Function The fdatasync() function is an inbuilt function in PHP that is used to synchronize changes to a file's data with the underlying storage device. This function is similar to the fsync() function, but it only synchronizes the file's data, not its metadata. Syntax: bool fdatasync(resource $stream) Param
1 min read
How to create an Asynchronous function in Javascript? JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations. Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title
6 min read
How to Delay a Function Call in JavaScript ? Delaying a JavaScript function call involves executing a function after a certain amount of time has passed. This is commonly used in scenarios where you want to postpone the execution of a function, such as in animations, event handling, or asynchronous operations. Below are the methods to delay a
2 min read
How to Write Asynchronous Function for Node.js ? The asynchronous function can be written in Node.js using 'async' preceding the function name. The asynchronous function returns an implicit Promise as a result. The async function helps to write promise-based code asynchronously via the event loop. Async functions will always return a value.Await f
2 min read