Add queueing to angulars $http service

前端 未结 6 1468
迷失自我
迷失自我 2020-12-07 17:24

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

6条回答
  •  天命终不由人
    2020-12-07 17:40

    .factory('qHttp', function($q, $http) {
      var queue = $q.when();
    
      return function queuedHttp(httpConf) {
        var f = function(data) {
          return $http(httpConf);
        };
        return queue = queue.then(f, f);
      };
    })
    

    How to use:

    var apis = ['//httpbin.org/ip', '//httpbin.org/user-agent', '//httpbin.org/headers'];
    
    for (var i = 0; i < 100; i++) {
      qHttp({
        method: 'get', 
        url: apis[i % apis.length]
      })
      .then(function(data) { 
        console.log(data.data); 
      });
    }
    

提交回复
热议问题