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

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

问题描述

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

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天全站免登陆