如何并行运行生成器函数? [英] How to run Generator Functions in Parallel?

查看:103
本文介绍了如何并行运行生成器函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一台Koa Web服务器,其端点如下:

Assuming I have a Koa web server with an endpoint like this:

const perform = require(...); // some generator function

exports.endpoint = function* () {

    var results = yield getResults();

    // Respond the results
    this.body = results;
}

exports.getResults = function* () {

    var actions = [...];
    var results = [];

    for (var action of actions) {

        var result = yield perform(action);

        results.push(results);
    }

    return results;
}

现在,在所有动作都明显执行之后,客户端将获得响应.但是事情是每一个动作都取决于前一个动作的完成.

Now the client will get the respond after ALL the actions are performed obviously. but the things is each action is dependent on the completion of the previous.

有没有办法并行执行它们?

Is there a way to execute them in parallel?

注意:除非我能以某种方式返回结果,而不是将它们解析(),否则将它们转换为Promises是不可行的.

Note: Turning them to Promises is not an option, unless I can somehow return the results, and not resolve() them.

推荐答案

co将生成器功能转换为Promises,并异步执行它们. Promise.all等待它们全部完成:

co turns the generator function to Promises, and executes them async. Promise.all waits for all of them to finish:

exports.getResults = function* () {

    var actions = [...];

    return yield Promise.all(actions.map(function(action) { 
        return co(function*() { 
            return yield perform(action); 
        } 
    }));
}

这篇关于如何并行运行生成器函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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