产生依赖于递归的承诺的承诺 [英] Produce a promise which depends on recursive promises

查看:134
本文介绍了产生依赖于递归的承诺的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有整数ID,如

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

和我有必要进行,每一这些ID的异步远程调用。每个呼叫使用$资源和psented作为承诺$ P $一个要求的WebAPI执行。

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.

我需要创建一个函数,这些ID的数组,然后初始化递归承诺链。链应导致相应的WebAPI呼叫对每个ID的,一个接一个。这些调用不应该是平行的,但链接。

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.

问题该函数返回本身就是一个主的承诺,应该基于对异步Web调用的结果得到解决或拒绝。也就是说,如果在recursuion一些承诺被拒绝,由于从服务器断开,还承诺主要应该失败。在正常情况下,主的承诺必须在该点时,所有的请求都完成解决。

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.

我怎样才能做到在angularjs?

How can I accomplish that in angularjs?

推荐答案

您使用减少数组链的承诺一起过来。有没有必要做这个递归。

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

这篇关于产生依赖于递归的承诺的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆