Produce a promise which depends on recursive promises

后端 未结 2 526
醉酒成梦
醉酒成梦 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([]));
    
    0 讨论(0)
  • 2020-11-30 15:14

    This is actually a very reasonable request.

    The tool we use for this in libraries without a specific .each control is .then:

    var a = [1,2,3,4,5];
    var p = makeRequest(a.shift()); // use first element
    a.forEach(function(el){
        p = p.then(function(result){
            return makeRequest(el);
        });
    });
    
    p.then(function(){
        // all requests done
    });
    

    Note that I assume you have a makeRequest method here that makes a single request and returns a promise that fulfills when that request is done.

    It's also possible to return the results of the requests if you need that using a secondary array:

    var a = [1,2,3,4,5];
    var results = Array(a.length);
    var p = makeRequest(a.shift()).
            then(function(res){ results[0] = res;}); // use first element
    a.forEach(function(el,i){
        p = p.then(function(result){
            results[i] = result;
            return makeRequest(el);
        });
    });
    p = p.thenResolve(results); // resolve with results, in BB that'd be p.return(results)
    
    p.then(function(results){
        // all requests done
        console.log(results); // array of response values
    }).catch(function(e){
        // single failure
    });
    

    Using the v2 branch of the Bluebird library, you can do:

     Promise.each([1,2,3,4,5],makeRequest).then(function(results){
          // access results
     });
    
    0 讨论(0)
提交回复
热议问题