如何运行“ x”并行Java承诺 [英] How to run "x" promises in parallel Javascript

查看:73
本文介绍了如何运行“ x”并行Java承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数 promiseFunction,该函数返回一个promise,稍后会被解决。

I have a function "promiseFunction" which returns a promise, which is resolved at a later time.

我需要多次调用此函数,但是我只希望一次执行该函数的一定数量的执行。

I need to call this function many times, however I only want a set number of executions of this function to happen at once.

该函数在我的计算机上调用一些外部单线程c代码,如果我一次使该代码的实例过多,则使系统崩溃,但如果按顺序调用一次1很慢,因为我的cpu上只有一个线程正在执行任何工作。

The function calls some external single threaded c code on my computer, if I call too many instances of this code at once I crash my system, but if I call it sequentially 1 at a time it's very slow as only one thread of my cpu is doing any work.

所以我想出了下面的代码,但是它不起作用。它会并行调用前10个诺言,但慢慢地,它会立即一次调用越来越少的诺言,直到一次只调用1个诺言。

So I came up with the code below, however it doesn't work. It will call the first 10 promises in parallel, but slowly it starts to call less and less promises at once, until it's only calling 1 promise at a time.

var totalNumberOfPromises = // total number times to run promiseFunction;
var promiseCounter = 0; // keep track of which promise call this is 
for(w=0;w<10;w++){ // run 10 promises at a time
  promiseFunction().then(function(resolve) {
    loadNewPromise();
  })
  promiseCounter++;
}

function loadNewPromise(){

  if(promiseCounter<totalNumberOfPromises){
    promiseFunction().then(function(resolve) {  loadNewPromise(); });
  }else{
    alert("Finished");
  }
  promiseCounter++;
}

上面的代码是否有任何错误导致此行为?并有标准的方法吗?

Is there anything wrong with the code above that causes this behavior? And is there a standard way of doing this?

推荐答案

这是我之前准备的功能(我已经使用了几个这样的东西已经有几年了

Here's a function I prepared earlier (I've used this for a few years now for just such a thing

const multiQueue = length => {
    length = (isNaN(length) || length < 1) ? 1 : length;
    const q = Array.from({length}, () => Promise.resolve());
    let index = 0;
    const add = cb => {
        index = (index + 1) % length;
        return (q[index] = q[index].then(() => cb()));
    };
    return add;
};

// demo usage

const q = multiQueue(10);

let inFlight = 0;
let maxInFlight = 0;
const promiseFunction = (i) => {
  	inFlight++;
    maxInFlight = Math.max(inFlight, maxInFlight);
    const obj = {inFlight, maxInFlight, i};
    return new Promise(resolve => {
        setTimeout(() => {
            inFlight--;
            resolve(Object.assign(obj, {t:performance.now()}));
        }, 10 );
    })
};

for (let i = 0; i < 40; i++) {
    q(() => promiseFunction(i)).then(v => console.log(JSON.stringify(v)));
}

您最多可以看到10个机上请求

You can see that at most there are 10 "inFlight" requests

这篇关于如何运行“ x”并行Java承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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