angularjs 链 http 发布顺序 [英] angularjs chain http post sequentially

查看:23
本文介绍了angularjs 链 http 发布顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我将数据存储在本地存储中并在后台触发异步 http 发布.一旦成功发布,发布的数据就会从本地存储中删除.当http post处理时,可能有更多的数据添加到本地存储,所以我需要将post排队并顺序处理它,因为我需要等待本地存储从成功的post中清除.应递归调用该任务,直到本地存储中有数据.

In my application, I am storing data in local storage and trigger async http post in the background. Once successfully posted, the posted data gets removed from local storage. When http post is in process, there may be more data added to local storage so I need to queue up the post and sequentially process it because, I need to wait for the local storage to be cleared from the successful posts. The task should be called recursively until there is data in local storage.

taskQueue: function () {
    var deferred = $q.defer();
    queue.push(deferred);
    var promise = deferred.promise;

    if (!saveInProgress) {
      // get post data from storage
      var promises = queue.map(function(){$http.post(<post url>, <post data>).then(function(result){
          // clear successful data
          deferred.resolve(result);
      }, function(error){
         deferred.reject(error);
      })
    })

    return $q.all(promises);
}

作为有角度的新手,我遇到了上面代码不连续的问题.我怎样才能实现我想要的?队列长度未知,并且队列长度随着进程的进行而增加.如果这是重复的,请指出其他答案.

As angular newbie, I am having problems with the above code not being sequential. How can I achieve what I intend to? The queue length is unknown and also the queue length increases as the process is in progress. Please point me to other answers if this is a duplicate.

推荐答案

Async.js 听起来不错,但如果您不想使用库...

Async.js sounds a good idea but if you don't want to use a library ...

$q.all 将批量处理一系列请求并同时触发它们,并在数组中的所有承诺都解决时解决 - 这不是您想要的.

$q.all will batch up an array of requests and fire them at the same time and will resolve when ALL promises in the array resolve - WHICH IS NOT WHAT YOU WANT.

要从数组中按顺序进行 $http 调用,请执行此操作....

to make $http calls SEQUENTIALLY from an array do this ....

var request0 = $http.get('/my/path0');
var request1 = $http.post('/my/path1', {data:'fred'});
var request2 = $http.get('/my/path2');
var requestArray = [];

然后……

requestArray.push(request0);
requestArray.push(request1);
requestArray.push(request2);

然后……

requestArray[0].then(function(response0) {
    // do something with response0
    return requestArray[1];
}).then(function(response1) {
    // do something with response1
    return requestArray[2];
}).then(function(response2) {
    // do something with response2
}).catch(function(failedResponse) {
    console.log("i will be displayed when a request fails (if ever)", failedResponse)
});

这篇关于angularjs 链 http 发布顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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