javascriptfibers

JavaScript native fibers


Do you know if native fiber support is planned in a future version of JavaScript? Indeed, it would be very cool if it was possible to write something like :

console.log("sleep 3s...");

const value = wait (resolve, reject) => {
    setTimeout(
        () => resolve(5),
        3_000
    );
};

console.log("value =", value);    // value = 5 (after 3s)

Of course it is possible to have a similar result with async/await but the fibers would allow you to pause anywhere in the code without having to be in a function declared async.

Indeed it can become very problematic to convert a synchronous function into an asynchronous one because it is necessary to transform all the dependencies in cascade:

const a = () => b() + 1;
const b = () => c() + 2;
const c = () => 5;
const value = a();

Ok now c becomes asynchronous...

const a = async () => (await b()) + 1;
const b = async () => (await c()) + 2;
const c = async () => new Promise(resolve => { ... resolve(5) });
const value = await a();

This is a simple example! With fiber, it would be much easier:

const c = () => wait resolve => { ... resolve(5) }

No need to modify a nor b !

PHP has implemented fibers since version 8 :

https://www.php.net/manual/en/language.fibers.php

Thank you in advance!


Solution

  • As I far as I know, fiber is not currently planned for a future version of javascript and probably will never be, as javascript is not multithreaded and does not suffer synchronization issues.

    Javascript implementations follow more or less the ECMAscript standards. You can follow the past and planned evolution on the ecma website and the draft specification.

    As far as I understand fiber, it looks like a way for controlling concurrency in php and I cannot see any use case in javascript. Asynchronicity should be explicit and stopping an execution flow this way does not seem appropriate in Javascript (considering the browser or a node environment).

    That said, as you said it can be explicitly implemented in current js (with promises and/or async/await function), and ES2022 introduced a module level await that will turn importing a module with such a construct into an implicit await before the code can be used.