Produce a promise which depends on recursive promises

后端 未结 2 540
醉酒成梦
醉酒成梦 2020-11-30 14:13

I have an array of integer ids, such as

var a=[1,2,3,4,5]

and I have a need to perform asynchronous remote calls for each of these ids. Ea

2条回答
  •  佛祖请我去吃肉
    2020-11-30 15:01

    You use reduce over the array to chain the promises together. There is no need make this recursive.

    // for angularjs: var Q = $q.when;
    var p = a.reduce(function(prev, el) {
        return prev.then(function(arr) {
            return makeRequest(el).then(function(res) {
                 return arr.concat([res]);
             });
        });
    }, Q([]));
    

提交回复
热议问题