支持Chrome浏览器的基于生成器的Java协程库 [英] Generator based Javascript coroutine library supporting Chrome browser

查看:132
本文介绍了支持Chrome浏览器的基于生成器的Java协程库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript生成器不能提供太多帮助,因为它不是真正的协程.因此,我希望使用一些新的ecmascript 6关键字"yield"在浏览器中具有协程.也就是说,我希望我可以在调用堆栈的多个帧中产生结果.

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.

据我所知,我刚刚在Firefox上找到了一个基于Javascript 1.7+的协程库,该库可以在

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".因此,我想知道是否有一个协程实现使用Javascript生成器支持Chrome浏览器.

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

谢谢!

推荐答案

Q库提供了 async 方法

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!");
    });
}

这里是 工作的小提琴 .在运行它之前,请确保在Chrome(chrome://flags/#enable-javascript-harmony)中启用JavaScript Harmony.

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

这篇关于支持Chrome浏览器的基于生成器的Java协程库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆