简体   繁体   English

使用Angular的resolve:时,兑现承诺的最佳方法是什么?

[英]What is the best way to chain promises when using Angular's resolve: {}?

I am using angular's resolve and would like to chain two promises. 我正在使用angular的解决方案,并希望实现两个承诺。 What is the best way of going about this? 最好的方法是什么? In essence, I want: 本质上,我想要:

resolve: {
    my_two_lists: function() {
    return MyService.list().then(function(array1) {     
         return MyOtherService.list().then(function(array2) { 
               return new Promise(function(resolve, reject) { 
                    resolve(array1.concat(array2)); 
               }); 
          }); 
       });
    }
}

In other words: I have 2 services, each with two methods called "list" that return, well, a promise which resolve to lists. 换句话说:我有2个服务,每个服务都有两个称为“列表”的方法,这些方法返回一个可以解析为列表的promise。 I would like to chain the two resulting promises. 我想将两个由此产生的诺言联系起来。

Something I've learned with Javascript promises - if you have more than one level of nesting, there will be a better way. 我从Javascript承诺中学到的知识-如果您具有多个层次的嵌套,将有更好的方法。

Here's a cleaner solution where you invoke the two list commands in parralel. 这是一个更清洁的解决方案,您可以在其中并行调用两个list命令。

resolve: {
    my_two_lists: function() {
            return Promise.all([MyService.list(), MyOtherService.list()])
                   .then(function(values) {
                        return values[0].concat(values[1]));
                   });
    }
}

If, for some reason, you wanted to call them one after the other, then your example is correct, except there's no need to return yet another promise. 如果出于某种原因,您想要一个接一个地称呼它们,那么您的示例是正确的,除了无需再返回另一个承诺。 Just return a value. 只需返回一个值。 The result of my_two_lists will still be a promise that resolves to the concatenation of the two arrays. my_two_lists的结果仍然是一个承诺,可以解决两个数组的串联问题。

resolve: {
    my_two_lists: function() {
    return MyService.list().then(function(array1) {     
         return MyOtherService.list().then(function(array2) { 
               return array1.concat(array2);
          }); 
       });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM