Generator based Javascript coroutine library supporting Chrome browser
Asked Answered
C

1

1

Javascript generator cannot help too much since it is not a real coroutine. So I hope to have coroutine in browser using some new ecmascript 6 keyword, "yield". i.e., I hope I can yield across multiple frames in the callstack.

To my knowledge, I just found a coroutine library based on Javascript 1.7+ on Firefox which can be found at http://www.neilmix.com/2007/02/07/threading-in-javascript-17/.

"yield" has been supported in Chrome browser for a long time. So I am wondering there is a coroutine implementation supporting Chrome browser using Javascript generator.

Thank you!

Calycine answered 4/2, 2014 at 2:57 Comment(1)
Maybe read this "more" current blog post: calculist.org/blog/2011/12/14/…Peder
H
1

Q library provides async method to wrap a JavaScript generator function. Inside the generator function, you can asynchronously await any Q promise object with yield keyword, for example:

function delay(ms) {
    var deferred = Q.defer();
    setTimeout(deferred.resolve, ms);
    return deferred.promise;
}

function main()
{
    var callback = Q.async(function*(){
        var bodyStyle = document.body.style;

        yield delay(1000);
        bodyStyle.backgroundColor = "red";
        printOutput("step 1");

        yield delay(1000);
        bodyStyle.backgroundColor = "green";
        printOutput("step 2");

        yield delay(1000);
        bodyStyle.backgroundColor = "blue";
        printOutput("step 3");

        yield delay(1000);
        printOutput("step 4");
        bodyStyle.backgroundColor = "white";
    });

    Q.fcall(callback).then(function (){
        printOutput("Done!");
    });
}

Here is a working fiddle. Before running it, make sure to enable JavaScript Harmony in Chrome (chrome://flags/#enable-javascript-harmony).

Huppert answered 4/2, 2014 at 4:58 Comment(2)
Thank you. Q is interesting. However, it is still not super natural. If some library behaves like a Windows fiber, that would be cool.Calycine
@LinZ, the closest thing like that you can get for JavaScript is waitfor-ES6, but it's Node.js-specifics. OTOH, Q promises + generators are more like Task objects and async/await in C# 5.0, something I'd currently prefer over anything else. Feel free to answer your own question if you find something else which suits you better.Huppert

© 2022 - 2024 — McMap. All rights reserved.