Dynamic Chaining in Javascript Promises

后端 未结 8 1298
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 20:42

How can I perform dynamic chaining in Javascript Promises, all the time I have seen only hardcoding of the calls for eg., (promise).then(request/funct

8条回答
  •  醉梦人生
    2020-12-08 20:57

    I just had a problem with my api provider that doing Promise.all() would end up in concurrency db problems..

    The deal with my situation is that i need to get every promise result in order to show some "all ok" or "some got error" alert.

    And i don't know why .. this little piece of code who uses reduce when the promises resolved i couldn't get my scope to work (too late to investigate now)

    $scope.processArray = function(array) {
        var results = [];
        return array.reduce(function(p, i) {
            return p.then(function() {
                return i.then(function(data) {
                    results.push(data);
                    return results;
                })
            });
        }, Promise.resolve());
    }
    

    So thanks to this post http://hellote.com/dynamic-promise-chains/ I came with this little bastard.. It's not polished but it's working all right.

    $scope.recurse = function(promises, promisesLength, results) {
    
        if (promisesLength === 1) {
            return promises[0].then(function(data){
                results.push(data);
                return results;
            });
        }
    
        return promises[promisesLength-1].then(function(data) {
            results.push(data);
            return $scope.recurse(promises, promisesLength - 1, results);
        });
    
    }
    

    Then i invoke the function like this:

    var recurseFunction = $scope.recurse(promises, promises.length, results);
    recurseFunction.then(function (response) { ... });
    

    I hope it helps.

提交回复
热议问题