加入排队angulars $ http服务 [英] Add queueing to angulars $http service
问题描述
我有一个非常古怪的API,它只能同时处理一个请求。
因此,我需要确保每一次请求时,它进入一个队列,该队列执行一次一个请求,直到它是空的。
I have a very quirky api that can only handle a single request at a time. Therefore, I need to ensure that every time a request is made, it goes into a queue, and that queue is executed one request at a time, until it is empty.
通常情况下,我只使用jQuery内置的队列,因为该网站已经在使用jQuery。但是,我不知道如果我能以某种方式装饰$ http服务,或者在一次返回一行诺言另一服务,还是其他什么东西包裹。
Normally, I just use jQuery's built in queue, since the site is already using jQuery. However, I was not sure if I could somehow decorate the $http service, or wrap it in another service that returns one promise at a time, or something else.
推荐答案
下面是我的解决办法: http://plnkr.co/编辑/ Tmjw0MCfSbBSgWRhFvcg
Here is my solution for that: http://plnkr.co/edit/Tmjw0MCfSbBSgWRhFvcg
的理念是:服务的每个运行添加请求排队并返回承诺。当请求的$ HTTP完成决心/拒绝归还承诺,从队列执行下一个任务(如有)。
The idea is: each run of service add request to queue and return promise. When request to $http is finished resolve/refuse returned promise and execute next task from queue if any.
app.factory('srv', function($q,$http) {
var queue=[];
var execNext = function() {
var task = queue[0];
$http(task.c).then(function(data) {
queue.shift();
task.d.resolve(data);
if (queue.length>0) execNext();
}, function(err) {
queue.shift();
task.d.reject(err);
if (queue.length>0) execNext();
})
;
};
return function(config) {
var d = $q.defer();
queue.push({c:config,d:d});
if (queue.length===1) execNext();
return d.promise;
};
});
看起来相当简单:)
Looks quite simple :)
这篇关于加入排队angulars $ http服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!