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

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

问题描述

我有一个整数 id 数组,例如

I have an array of integer ids, such as

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

而且我需要为这些 id 中的每一个执行异步远程调用.每个调用都是一个使用 $resource 执行的 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 数组的函数,然后初始化递归承诺链.该链应该为每个 ID 一个接一个地产生相应的 webapi 调用.这些调用不应该是并行的,而应该是链接的.

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.

有问题的函数自身返回一个主要"承诺,应根据异步网络调用的结果解析或拒绝该承诺.也就是说,如果递归中的某些承诺由于与服务器断开连接而被拒绝,则主要承诺也应该失败.在正常情况下,main"promise 必须在所有请求完成时解析.

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?

推荐答案

您可以在数组上使用 reduce 将 promise 链接在一起.没有必要使这个递归.

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天全站免登陆