Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

javascript - Produce a promise which depends on recursive promises

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. Each call is a WebAPI request performed using $resource and presented as promise.

I need to create a function that takes array of these IDs, then initializes recursive promises chain. The chain should result in consequential webapi calls for each of IDs, one by one. These calls should not be parallel but chained.

The function in question returns itself a "main" promise that should be resolved or rejected based on result of asynchronous web calls. That is, if some promise in the recursuion is rejected due to disconnection from server, the main promised also should fail. In normal case, "main" promise must resolve at the point when all requests are completed.

How can I accomplish that in angularjs?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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([]));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...