Skip to content

Is it possible to export the code of the main loop as a function, so that there is no need to write a callback function. #213

@pixelvm

Description

@pixelvm

PHP does not have async/wait syntax. Is it possible to add a function to call the main loop code so that we can write synchronous code instead of callback functions.

<?php

class Loop {
    function loopTick () {
        // ...
    }

    function run () {
        while (loopTick()) {}
    }
}

// function wait run the function loopTick likely $loop->run(), and block the current thread until promise settled.
function waitPromiseSettled ($promise) {
    $rejected = false;
    $resolved = false;
    $error = null;
    $ret = null;
    $promsie->then(function ($val) use (&$resolved, &$ret) {
        $ret = $val;
        $resolved = true;
    })->catch(function ($err) use (&$rejected, &$error) {
        $error = $err;
        $rejected = true;
    });
    while (loopTick()) {
        if ($resolved) {
            return $ret;
        } else if ($rejected) {
            throw $error;
        }
    }
    throw new Exception("...");
}

class Promise {
    function resolve () {
        // ...
    }

    function reject () {
        // ...
    }

    function wait () {
        return waitPromiseSettled($this);
    }
}

// coding sync 
$value = new Promise(function (/* ... */) { /* ... */ })->wait();

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions