PHP code example of drewlabs / async

1. Go to this page and download the library: Download drewlabs/async library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

drewlabs / async example snippets


 
$promise = async(function () {
	printf("Calling coroutine...\n");
	usleep(1000 * 2000);
	return 'awaited';
});
$promise->then(function($value) {
	printf("%s...", $value); // awaited...
});

  $promise = promise(function($resolve, $reject) {
       // Do something with resolve
       usleep(1000*1000); // Block PHP execution
       resolve("I have been waited for 1 second.");
  });
  // Wait for the promise
  $promise->wait();
  

  // Here the script create a promise instance that executes when
  // PHP process shutdown with success
  $promise = promise(function($resolve, $reject) {
       // Do something with resolve
       usleep(1000*1000); // Block PHP execution
       resolve("I have been waited for 1 second.");
  }, true);
  


// Here the script create a promise instance that executes when
// PHP process shutdown with success

$promise = defer(function($resolve, $reject) {
     // Do something with resolve
     usleep(1000*1000); // Block PHP execution
     resolve("I have been waited for 1 second.");
});



$promise = join(
    function () {
        printf("Calling coroutine...\n");
        yield usleep(1000*2000); // blocking
        return'awaited';
    },
    function () {
        printf("Calling second coroutine...\n");
        yield usleep(1000*2000); // blocking
        return'awaited 2';
    },
);


$promise->then(function($value) {
     print_r($value); // ['awaited', 'awaited 2']
});
// ...
// Start the async routine
$promise->wait();


  $promise = async(function () {
       yield usleep(1000 * 500);
       return 2;
  });

  // ...
  // Awaiting the coroutine
  $result = await($promise);
  printf("%d\n", $result); // 2 

  // Developpers can directly call / await on a given subroutine
  $result2 = await(function () {
       yield usleep(1000 * 500);
       return 2;
  }); 

  printf("%d\n", $result2); // 2