简体   繁体   English

如何并行运行生成器函数?

[英]How to run Generator Functions in Parallel?

Assuming I have a Koa web server with an endpoint like this:假设我有一个 Koa web 服务器,端点如下:

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?有没有办法并行执行它们?

Note: Turning them to Promises is not an option, unless I can somehow return the results, and not resolve() them.注意:将它们转换为 Promises 不是一种选择,除非我可以以某种方式返回结果,而不是 resolve() 它们。

co turns the generator function to Promises, and executes them async. co将生成器功能转换为Promises,并异步执行它们。 Promise.all waits for all of them to finish: Promise.all等待它们全部完成:

exports.getResults = function* () {

    var actions = [...];

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

If the generators are used as coroutines, by simulating the async / await flow, then you should be able to do: 如果将生成器用作协程,则通过模拟async / await流,您应该能够:

var results = yield Promise.all(actions.map(action => perform(action)));

or even: 甚至:

var results = yield Promise.all(actions.map(perform));

I'm not sure about the exact usage here but when you use generators with co or Bluebird.coroutine then you're already using promises, so you may as well use them more explicitly. 我不确定这里的确切用法,但是当您将生成器与coBluebird.coroutine一起使用时,您已经在使用promise,因此也可以更明确地使用它们。

So, instead of: 因此,代替:

exports.getResults = function* () {

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

    for (var action of actions) {

        var result = yield perform(action);

        results.push(results);
    }

    return results;
}

you can try: 你可以试试:

exports.getResults = function* () {

    var actions = [...];

    return yield Promise.all(actions.map(perform));
}

if you are using redux saga than follow this link如果您使用的是 redux 传奇,请访问此链接

https://redux-saga.js.org/docs/advanced/RunningTasksInParallel/ https://redux-saga.js.org/docs/advanced/RunningTasksInParallel/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM