NodeJS 限制挂起承诺的并发性

vngu2lb8  于 2023-02-15  发布在  Node.js
关注(0)|答案(5)|浏览(164)

我正在寻找一个promise函数 Package 器,它可以在给定的promise运行时进行限制/节流,以便在给定的时间只有一组数量的promise运行。
在下面的情况下,delayPromise不应该并发运行,它们应该按照先到先得的顺序一次运行一个。

import Promise from 'bluebird'

function _delayPromise (seconds, str) {
  console.log(str)
  return Promise.delay(seconds)
}

let delayPromise = limitConcurrency(_delayPromise, 1)

async function a() {
  await delayPromise(100, "a:a")
  await delayPromise(100, "a:b")
  await delayPromise(100, "a:c")
}

async function b() {
  await delayPromise(100, "b:a")
  await delayPromise(100, "b:b")
  await delayPromise(100, "b:c")
}

a().then(() => console.log('done'))

b().then(() => console.log('done'))

有什么办法能让这样的队伍排起来吗?
我有一个来自Benjamin Gruenbaum的“debounce”函数,我需要修改这个函数,根据它自己的执行而不是延迟来限制一个承诺。

export function promiseDebounce (fn, delay, count) {
  let working = 0
  let queue = []
  function work () {
    if ((queue.length === 0) || (working === count)) return
    working++
    Promise.delay(delay).tap(function () { working-- }).then(work)
    var next = queue.shift()
    next[2](fn.apply(next[0], next[1]))
  }
  return function debounced () {
    var args = arguments
    return new Promise(function (resolve) {
      queue.push([this, args, resolve])
      if (working < count) work()
    }.bind(this))
  }
}
z6psavjg

z6psavjg1#

我不认为有任何库可以做到这一点,但实际上您自己实现起来相当简单:

function sequential(fn) { // limitConcurrency(fn, 1)
    let q = Promise.resolve();
    return function(x) {
        const p = q.then(() => fn(x));
        q = p.reflect();
        return p;
    };
}

对于多个并发请求,这会变得有点棘手,但也可以做到。

function limitConcurrency(fn, n) {
    if (n == 1) return sequential(fn); // optimisation
    let q = Promise.resolve();
    const active = new Set();
    const fst = t => t[0];
    const snd = t => t[1];
    return function(x) {
        function put() {
            const p = fn(x);
            const a = p.reflect().then(() => {
                active.delete(a);
            });
            active.add(a);
            return [Promise.race(active), p];
        }
        if (active.size < n) {
            const r = put()
            q = fst(t);
            return snd(t);
        } else {
            const r = q.then(put);
            q = r.then(fst);
            return r.then(snd)
        }
    };
}

顺便说一句,你可能想看看actors modelCSP。它们可以简化处理这类事情,也有一些JS库适合它们。

    • 示例**
import Promise from 'bluebird'

function sequential(fn) {
  var q = Promise.resolve();
  return (...args) => {
    const p = q.then(() => fn(...args))
    q = p.reflect()
    return p
  }
}

async function _delayPromise (seconds, str) {
  console.log(`${str} started`)
  await Promise.delay(seconds)
  console.log(`${str} ended`)
  return str
}

let delayPromise = sequential(_delayPromise)

async function a() {
  await delayPromise(100, "a:a")
  await delayPromise(200, "a:b")
  await delayPromise(300, "a:c")
}

async function b() {
  await delayPromise(400, "b:a")
  await delayPromise(500, "b:b")
  await delayPromise(600, "b:c")
}

a().then(() => console.log('done'))
b().then(() => console.log('done'))

// --> with sequential()

// $ babel-node test/t.js
// a:a started
// a:a ended
// b:a started
// b:a ended
// a:b started
// a:b ended
// b:b started
// b:b ended
// a:c started
// a:c ended
// b:c started
// done
// b:c ended
// done

// --> without calling sequential()

// $ babel-node test/t.js
// a:a started
// b:a started
// a:a ended
// a:b started
// a:b ended
// a:c started
// b:a ended
// b:b started
// a:c ended
// done
// b:b ended
// b:c started
// b:c ended
// done
vptzau2j

vptzau2j2#

使用限制承诺模块:
https://www.npmjs.com/package/throttled-promise

var ThrottledPromise = require('throttled-promise'),
    promises = [
        new ThrottledPromise(function(resolve, reject) { ... }),
        new ThrottledPromise(function(resolve, reject) { ... }),
        new ThrottledPromise(function(resolve, reject) { ... })
    ];

// Run promises, but only 2 parallel
ThrottledPromise.all(promises, 2)
.then( ... )
.catch( ... );
nom7f22z

nom7f22z3#

我也有同样的问题,我写了一个库来实现它,代码是here,我创建了一个队列来保存所有的承诺,当你把一些承诺推送到队列中时,队列头的前几个承诺会弹出并运行,一旦一个承诺完成,队列中的下一个承诺也会弹出并运行,一次又一次,直到队列中没有Task为止。详细信息可以查看代码。希望这个库对您有所帮助。

rseugnpd

rseugnpd4#

优点

  • 您可以定义并发承诺的数量(接近并发请求)
  • 一致流动:一旦一个承诺解决,另一个请求开始,无需猜测服务器的能力
  • 强大的抗数据阻塞能力,如果服务器停止了一会儿,它将只是等待,并且不会因为时钟允许而启动后续任务
  • 不要依赖第三方模块Vanila node.js

第一件事是让https成为一个承诺,所以我们可以使用wait来检索数据(从示例中删除)第二件事是创建一个承诺调度程序,在任何承诺得到解决时提交另一个请求。

通过限制并发承诺的数量来限制接受的请求

const https = require('https')

function httpRequest(method, path, body = null) {
  const reqOpt = { 
    method: method,
    path: path,
    hostname: 'dbase.ez-mn.net', 
    headers: {
      "Content-Type": "application/json",
      "Cache-Control": "no-cache"
    }
  }
  if (method == 'GET') reqOpt.path = path + '&max=20000'
  if (body) reqOpt.headers['Content-Length'] = Buffer.byteLength(body);
  return new Promise((resolve, reject) => {
  const clientRequest = https.request(reqOpt, incomingMessage => {
      let response = {
          statusCode: incomingMessage.statusCode,
          headers: incomingMessage.headers,
          body: []
      };
      let chunks = ""
      incomingMessage.on('data', chunk => { chunks += chunk; });
      incomingMessage.on('end', () => {
          if (chunks) {
              try {
                  response.body = JSON.parse(chunks);
              } catch (error) {
                  reject(error)
              }
          }
          console.log(response)
          resolve(response);
      });
  });
  clientRequest.on('error', error => { reject(error); });
  if (body) { clientRequest.write(body)  }  
  clientRequest.end();

  });
}

    const asyncLimit = (fn, n) => {
      const pendingPromises = new Set();

  return async function(...args) {
    while (pendingPromises.size >= n) {
      await Promise.race(pendingPromises);
    }

    const p = fn.apply(this, args);
    const r = p.catch(() => {});
    pendingPromises.add(r);
    await r;
    pendingPromises.delete(r);
    return p;
  };
};
// httpRequest is the function that we want to rate the amount of requests
// in this case, we set 8 requests running while not blocking other tasks (concurrency)

let ratedhttpRequest = asyncLimit(httpRequest, 8);

// this is our datase and caller    
let process = async () => {
  patchData=[
      {path: '/rest/slots/80973975078587', body:{score:3}},
      {path: '/rest/slots/809739750DFA95', body:{score:5}},
      {path: '/rest/slots/AE0973750DFA96', body:{score:5}}]

  for (let i = 0; i < patchData.length; i++) {
    ratedhttpRequest('PATCH', patchData[i].path,  patchData[i].body)
  }
  console.log('completed')
}

process()
6gpjuf90

6gpjuf905#

串行运行异步进程的经典方法是使用async.jsasync.series(),如果您更喜欢基于promise的代码,那么有一个promise版本的async.jsasync-q
对于async-q,您可以再次使用series

async.series([
    function(){return delayPromise(100, "a:a")},
    function(){return delayPromise(100, "a:b")},
    function(){return delayPromise(100, "a:c")}
])
.then(function(){
    console.log(done);
});

同时运行其中两个将同时运行ab,但在每个内部它们将是顺序的:

// these two will run concurrently but each will run
// their array of functions sequentially:
async.series(a_array).then(()=>console.log('a done'));
async.series(b_array).then(()=>console.log('b done'));

如果您想在a之后运行b,请将其放入.then()

async.series(a_array)
.then(()=>{
    console.log('a done');
    return async.series(b_array);
})
.then(()=>{
    console.log('b done');
});

如果您不想按顺序运行每个进程,而是想限制每个进程同时运行一定数量的进程,则可以使用parallelLimit()

// Run two promises at a time:
async.parallelLimit(a_array,2)
.then(()=>console.log('done'));

阅读async-q文档:https://github.com/dbushong/async-q/blob/master/READJSME.md

相关问题