Dynamic clicking on the $ q.all () array

Basically I am trying to create a promise queue in angular, which works kinda like $q.all(), but only allows me to push more promises to the array after it is $q.all() executed, for example.

To try and explain better, imagine that a function makes a single promise for which you want to execute some code for then(). However, while you wait for this first promise, you give a second promise to this function. Now I do not want to be then()called until both have completed (similarly $q.all()). If the first promise is completed before the second is provided, the function then()will be called twice. This should work for an arbitrary number of promises.

Essentially, you get a promise queue that executes then()once every time the queue has been emptied (i.e., all currently provided promises have been resolved). I'm sure I can find a good way to do this, just by seeing that someone from the SO city has already implemented something, or is there a simple option that I miss.

+4
source share
1 answer

I came across something similar, maybe that would be helpful.

AJAX , . AJAX, , AJAX, . , , , .

$q.all , , promises, , promises .

( , ) , $q.all, .

var promisesArr = [];
var unresolved = 0;

function getChildNodes(node) {
   var url = BASE_URL + '/' + node.id;
   var prom = $q(function (resolve, reject) {
            unresolved++;
            $http.get(url).then(function (resp) {
            angular.forEach(resp.data.children, function(v){
               var newNode = {};
               newNode.id = v.id;
               getChildNodes(newNode);
               node.children.push(newNode);
            });
            resolve();
            unresolved--;
            }, function () {
                // Need to handle error here
                console.log('ERROR');
                reject();
                unresolved--;
            })
         });
    promisesArr.push(prom);
}

rootNode = {id: 1}
getChildNodes(rootNode);

allResolved();

    function allResolved() {
        if (unresolved > 0) {
            $q.all(promisesArr).then(allResolved);
        } else {
            RenderTree(rootNode);
        }
    }
0

Source: https://habr.com/ru/post/1547695/


All Articles