Generator based Javascript coroutine library suppo

2019-07-30 15:02发布

问题:

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!

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