将排队添加到 angulars $http 服务 [英] Add queueing to angulars $http service

查看:23
本文介绍了将排队添加到 angulars $http 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常古怪的 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 服务,或者将其包装在另一个一次返回一个 promise 的服务中,或者其他什么.

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/edit/Tmjw0MCfSbBSgWRhFvcg

这个想法是:每次运行的服务将请求添加到队列并返回承诺.当对 $http 的请求完成时,resolve/refuse 返回 promise 并执行队列中的下一个任务(如果有).

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;
  };
});

看起来很简单:)

这篇关于将排队添加到 angulars $http 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆