我正在寻找一个promise函数包装器,它可以在给定的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
获得了“去抖动”功能。我需要修改它来根据它自己的执行而不是延迟来限制一个承诺。
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))
}
}
答案 0 :(得分:6)
我认为没有任何库可以做到这一点,但实际上实现起来非常简单:
function queue(fn) { // limitConcurrency(fn, 1)
var q = Promise.resolve();
return function(x) {
var p = q.then(function() {
return fn(x);
});
q = p.reflect();
return p;
};
}
对于多个并发请求,它会变得有点棘手,但也可以完成。
function limitConcurrency(fn, n) {
if (n == 1) return queue(fn); // optimisation
var q = null;
var active = [];
function next(x) {
return function() {
var p = fn(x)
active.push(p.reflect().then(function() {
active.splice(active.indexOf(p), 1);
})
return [Promise.race(active), p];
}
}
function fst(t) {
return t[0];
}
function snd(t) {
return t[1];
}
return function(x) {
var put = next(x)
if (active.length < n) {
var r = put()
q = fst(t);
return snd(t);
} else {
var r = q.then(put);
q = r.then(fst);
return r.then(snd)
}
};
}
顺便说一下,您可能想查看actors model和CSP。他们可以简化这些事情的处理,也有一些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
答案 1 :(得分:0)
我有同样的问题。我写了一个库来实现它。代码是here。我创建了一个队列来保存所有的承诺。当你将一些promises推送到队列时,队列头部的前几个promises将会弹出并运行。一旦完成一个承诺,队列中的下一个承诺也将弹出并运行。一次又一次,直到队列没有Task
。您可以查看代码以获取详细信息。希望这个图书馆可以帮到你。
答案 2 :(得分:0)
- 您可以定义并发承诺的数量(在并发请求附近)
- 流程一致:一旦一个承诺解决,另一个请求就开始了,无需猜测服务器功能
- 防止数据阻塞,如果服务器停止一会儿,它将等待,而下一个任务将不会启动,因为 允许时钟
- 不要依赖于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()
答案 3 :(得分:-1)
使用throttled-promise模块:
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( ... );
答案 4 :(得分:-2)
串联运行异步流程的经典方法是使用async.js
并使用async.series()
。如果您更喜欢基于承诺的代码,则承诺版本为async.js
:async-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);
});
同时运行其中两个将同时运行a
和b
,但每个内部都会顺序运行:
// 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'));
如果您想在b
后运行a
,请将其放入.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