如何限制 Q promise 并发? [英] How can I limit Q promise concurrency?
问题描述
如何编写限制Q promise并发的方法?
How do I write a method that limits Q promise concurrency?
例如,我有一个方法 spawnProcess
.它返回一个 Q 承诺.
我希望一次生成的进程不超过 5 个,但对调用代码透明.
For instance, I have a method spawnProcess
. It returns a Q promise.
I want no more than 5 process spawned at a time, but transparently to the calling code.
我需要实现的是一个带签名的函数
What I need to implement is a function with signature
function limitConcurrency(promiseFactory, limit)
我可以这样称呼
spawnProcess = limitConcurrency(spawnProcess, 5);
// use spawnProcess as usual
我已经开始研究我的版本,但我想知道是否有人有我可以检查的简洁实现.
I already started working on my version, but I wonder if anyone has a concise implementation that I can check against.
推荐答案
我有一个库可以为您执行此操作 https://github.com/ForbesLindesay/throat
I have a library that does this for you https://github.com/ForbesLindesay/throat
您可以通过 browserify 使用它或从 brcdn (https://www.brcdn.org/?module=throat&version=latest) 并将其添加为脚本标记.
You can use it via browserify or download the standalone build from brcdn (https://www.brcdn.org/?module=throat&version=latest) and add it as a script tag.
然后(假设 Promise
构造函数是 polyfill 或在您的环境中实现)您可以执行以下操作:
Then (assuming the Promise
constructor is polyfilled or implemented in your environment) you can do:
//remove this line if using standalone build
var throat = require('throat');
function limitConcurrency(promiseFactory, limit) {
var fn = throat(promiseFactory, limit);
return function () {
return Q(fn.apply(this, arguments));
}
}
你可以直接调用 throat(promiseFactory, limit)
但这会返回一个 promise 承诺而不是 Q 承诺.
You could just call throat(promiseFactory, limit)
directly but that would return a promise promise rather than a Q promise.
我也非常喜欢将它与 array.map 一起使用.
I also really like using it with array.map.
// only allow 3 parallel downloads
var downloadedItems = Q.all(items.map(throat(download, 3)));
这篇关于如何限制 Q promise 并发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!