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
- Do you know if native fiber support is planned in a future version of JavaScript?
- Do you know if there is a place where we can see the future innovations planned in JavaScript?
- Is there a place where we can propose innovations for JavaScript?
- Do you think that native fiber support would be a good idea?
Thank you in advance!
2
Answers
Ok, thanks for your answer!
It is true that being able to "pause" at any point in the code can become a source of bugs if not handled properly. But
await
also introduces this danger because it allows other code portions to be executed in parallel. In other words, you have to be vigorous with the competition, putting locks where necessary.I have just created the topic on https://es.discourse.group/t/javascript-native-fibers/1281.
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 levelawait
that will turnimport
ing a module with such a construct into an implicit await before the code can be used.