处理多重承诺的结果 [英] handling the result of multiple promises

查看:80
本文介绍了处理多重承诺的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 1.X应用程序中,如果我想处理两个promise的结果,那么有比这更优雅的方法了:

In an Angular 1.X app, if I want to handle the result of two promises is there a more elegant way to achieve it than this:

function doSomethingWithBothResults(result1, result2) {
  return result 1 + result2;
}

$http.get('/endpoint1').then(function (result1) {

  $http.get('/endpoint2').then(function (result2) {
    doSomethingWithBothResults(result1 + result2);
  });
});

虽然只有2个诺言就可以了,但由于数量更多而导致的深层嵌套令人不安.

While this is fine when there are only 2 promises, the deep nesting that would result from a larger number is unsettling.

推荐答案

您可以使用对于您的代码段来说,应该是这样的:

It would be something like this for your snippet:

let promises = [];
promises.push($http.get('/endpoint1'));
promises.push($http.get('/endpoint2'));

Promise.all ( promises ).then ( function ( data ) {
    //Data from all the promises
} ).catch ( function ( error ) {
   //Error
} );

在回调函数 data 中是一个数组,其每个元素都包含promise的已解析值.此外, data 中元素的顺序与将它们压入数组的顺序相同.

In the callback function data is an array whose each element contains the resolved value of the promise. Moreover, the order of the elements in data is same as in which you pushed them in the array.

如果您的诺言彼此相互独立,这将很有用.如果他们需要先前承诺的结果,那么就可以采用链接方式.此外,这将开始同时解决两个诺言,而链接方法将等待一个解决,然后开始解决下一个诺言

This would be useful, if your promises are independent of each other. If they require the result of a previous promise, chaining is the way to go. Also, this will start resolving both promises at the same time, while the chaining approach will wait for one to resolve and then start resolving the next one

这篇关于处理多重承诺的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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