Generator based Javascript coroutine library supporting Chrome browser

扶醉桌前 提交于 2019-12-13 02:08:00

问题


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



来源:https://stackoverflow.com/questions/21542174/generator-based-javascript-coroutine-library-supporting-chrome-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!