Good day, everyone.

As I write more code examples, I'm starting to get annoyed by the verbosity
of the `spawn in $scope` construct—especially in situations where all
spawns need to happen within the same context.

At the same time, in 80% of cases, it turns out that explicitly defining
`$scope` is the only correct approach to avoid shooting yourself in the
foot.
So, it turns out that the `spawn in $scope` construct is used far more
frequently than a plain `spawn`.

I remembered an example that Larry came up with and decided to use it as
syntactic sugar.

There’s some doubt because the actual gain in characters is minimal. This
block doesn't change the logic in any way.
The convenience lies in the fact that within the block, it’s clear which
`$scope` is currently active.
However, this is more about visual organization than logical structure.

Here's what I ended up with:

### Async blocks

Consider the following code:

```php
function generateReport(): void
{
    $scope = Scope::inherit();

    try {
        [$employees, $salaries, $workHours] = await Async\all([
            spawn in $scope fetchEmployees(),
            spawn in $scope fetchSalaries(),
            spawn in $scope fetchWorkHours()
        ]);

        foreach ($employees as $id => $employee) {
            $salary = $salaries[$id] ?? 'N/A';
            $hours = $workHours[$id] ?? 'N/A';
            echo "{$employee['name']}: salary = $salary, hours = $hours\n";
        }

    } catch (Exception $e) {
        echo "Failed to generate report: ", $e->getMessage(), "\n";
    }
}
```

with async

```php
function generateReport(): void
{
    try {

        $scope = Scope::inherit();

        async $scope {
            [$employees, $salaries, $workHours] = await Async\all([
                spawn fetchEmployees(),
                spawn fetchSalaries(),
                spawn fetchWorkHours()
            ]);

            foreach ($employees as $id => $employee) {
                $salary = $salaries[$id] ?? 'N/A';
                $hours = $workHours[$id] ?? 'N/A';
                echo "{$employee['name']}: salary = $salary, hours =
$hours\n";
            }
        }

    } catch (Exception $e) {
        echo "Failed to generate report: ", $e->getMessage(), "\n";
    }
}

```

#### async syntax

```php
async <scope> {
    <codeBlock>
}
```

Reply via email to