我如何限制Q promise的并发? [英] How can I limit Q promise concurrency?
问题描述
我如何写一个限制Q promise并发的方法?
例如,我有一个方法 spawnProcess
。它返回一个Q promise。
我一次只能生成5个进程,但透明的调用代码。
我需要什么实现是一个带有签名的函数
函数limitConcurrency(promiseFactory,limit)
/ pre>
我可以调用像
spawnProcess = limitConcurrency spawnProcess,5);
//照常使用spawnProcess
我已经开始使用我的版本,但我不知道有没有一个简洁的实现,我可以检查。
解决方案我有一个库 https://github.com/ForbesLindesay/throat
您可以通过browserify使用它,也可以从brcdn下载独立版本( https:/ /www.brcdn.org/?module=throat&version=latest )并将其添加为脚本标记。
然后(假设
Promise
构造函数在你的环境中是polyfilled或实现的)你可以这样做:如果使用独立构建,请删除此行
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 promise,而不是Q promise。
我也非常喜欢使用array.map。
//只允许3个并行下载
var downloadedItems = Q.all(items.map(throat(download,3)));
How do I write a method that limits Q promise concurrency?
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)
that I can call like
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.
解决方案I have a library that does this for you https://github.com/ForbesLindesay/throat
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.
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)); } }
You could just call
throat(promiseFactory, limit)
directly but that would return a promise promise rather than a Q promise.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屋!