简体   繁体   English

如何在javascript中控制并发?

[英]How to control concurrency in javascript?

I need to control concurrency in a Node.js script I'm making. 我需要控制正在制作的Node.js脚本中的并发性。 Currently I'm trying to use npm promise-task-queue but I'm open to other suggestions. 目前,我正在尝试使用npm promise-task-queue,但是我愿意接受其他建议。

I'm not sure how to implement promise-task-queue into my code. 我不确定如何在我的代码中实现promise-task-queue。 This is my original program: 这是我的原始程序:

readURLsfromFile().then( (urls) => {

    urls.reduce( (accumulator, current, i) => {
        return accumulator.then( () => {
            return main(urls[i], i, urls.length)
        })
    }, Promise.resolve())
})

As you can see I'm reading urls from a file, then using .reduce() to run main() in serial on each one of these urls. 如您所见,我正在从文件中读取URL,然后使用.reduce()在这些URL的每一个上串行运行main()。 Serial was too slow though so I need to do it with controlled concurrency. 串行速度太慢了,所以我需要控制并发性。

Here's the code I started to write using promise-task-queue (It's very wrong, I have no idea what I'm doing): 这是我开始使用promise-task-queue编写的代码(这是非常错误的,我不知道自己在做什么):

var taskQueue = require("promise-task-queue");

var queue = taskQueue();
var failedRequests = 0;

queue.on("failed:apiRequest", function(task) {
    failedRequests += 1;
});

queue.define("apiRequest", function(task) {
    return Promise.try( () => {
        return main(urls[i], i, urls.length));
    }).then( () => {
        return console.log("DONE!");
    });
}, {
    concurrency: 2
});

Promise.try( () => {
    /* The following queues up the actual task. Note how it returns a Promise! */
    return queue.push("apiRequest", {url: urls[i], iteration: i, amountToDo: urls.length)});
})

As you can see I've put my main() function with its argument after the Promise.try, and I've put my arguments after the return queue.push. 如您所见,我将main()函数及其参数放在Promise.try之后,并将参数放在return queue.push之后。 Not sure if that's correct or not. 不确定是否正确。

But regardless now I'm stuck, how do I load all the iterations into the queue? 但是,不管现在我陷入困境,如何将所有迭代加载到队列中?

You could use the qew module from npm: https://www.npmjs.com/package/qew . 您可以使用来自npm的qew模块: https : //www.npmjs.com/package/qew

Install using npm install qew . 使用npm install qew

To initialise you do 要初始化你做

const Qew = require('qew');

const maxConcurrent = 3;
const qew = new Qew(maxConcurrent);

Using the above code qew will now be a queue that allows you to push asynchronous functions onto that will execute with a maximum concurrency of 3. 使用上面的代码qew现在将成为一个队列,允许您将异步函数压入队列,并以3的最大并发性执行。

To push a new async function onto the qew you can do 要将新的异步功能推入队列,您可以执行

qew.pushProm(asyncFunc);

So in your case if I understood you correctly you could do something like 因此,在您的情况下,如果我对您的理解正确,则可以执行类似

readURLsfromFile()
  .then(urls => {
    return Promise.all(urls.map(url => { // wait for all promises to resolve
      return qew.pushProm(() => main(url)); // push function onto queue
    }));
  })
  .then(results => {
    // do stuff with results
  })

In this snippet you are reading urls from a file, and then loading a bunch of functions into the qew one by one and waiting for them all to resolve before doing something with them. 在此代码段中,您正在从文件中读取URL,然后将一堆函数qew加载到qew ,并等待它们全部解析,然后再对其进行处理。

Full disclaimer: I am the author of this package. 完全免责声明:我是该软件包的作者。

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

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