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!

noseratio
  • 59,932
  • 34
  • 208
  • 486
Lin Z
  • 171
  • 2
  • 9
  • Maybe read this "more" current blog post: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/ – Bergi Feb 04 '14 at 14:31

1 Answers1

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).

noseratio
  • 59,932
  • 34
  • 208
  • 486
  • Thank you. Q is interesting. However, it is still not super natural. If some library behaves like a Windows fiber, that would be cool. – Lin Z Feb 04 '14 at 14:26
  • @LinZ, the closest thing like that you can get for JavaScript is [waitfor-ES6](https://github.com/luciotato/waitfor-ES6/blob/master/README.md), 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. – noseratio Feb 04 '14 at 14:30