drewlabs/async

提供PHP异步编程的实用函数

v0.1.6 2023-09-28 13:32 UTC

This package is auto-updated.

Last update: 2024-09-28 15:29:04 UTC


README

async库提供了一组实用函数,用于在PHP语言中进行基本的异步编程。它利用PHP的Generator来实现一个协程平台,异步任务在该平台上执行。

用法

该库提供了以下实用函数

  • async async(callable $waitFn)

async实用函数为作为参数传递的子例程提供了一个异步函数执行上下文。

它返回一个Awaitable实例,当对其调用wait()时开始执行子例程。当子例程完成时,wait()语句将暂停脚本执行。

<?php 
$promise = async(function () {
	printf("Calling coroutine...\n");
	usleep(1000 * 2000);
	return 'awaited';
});
$promise->then(function($value) {
	printf("%s...", $value); // awaited...
});
  • promise promise(callable $waitFn, bool $shutdown = false)

    promise提供了一个工厂函数,用于创建符合promise A+规范的实例。它接受一个带有对revolve函数引用的等待函数作为第一个参数,以及作为promise实例的reject函数引用的第二个参数。

    $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();

    注意在上面的示例中,如果不调用wait(),则不会执行promise协程。要创建一个在PHP进程关闭时自动执行的promise,工厂函数接受一个布尔标志作为参数。

    // 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);
  • defer defer(callable $waitFn)

// 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.");
});
  • defer创建一个promise实例,当PHP进程关闭时执行解析和拒绝回调。这是promise($waitFn, true)的简单版本。

join join(...$waitFn)

$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();
  • joinasync接口相同,除了它接受一个子例程列表,等待这些子例程的结果,并按插入顺序返回等待结果列表。

    $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 

    await & all await($coroutine) / all(array $coroutines) 这些是等待asyncjoin子例程的实用函数。