简体   繁体   English

$ q.all promise取决于另一个promise的结果

[英]$q.all promise depends on result of another promise

I currently have three nested promises which I want to turn into a $q.all call. 我目前有三个嵌套的Promise,我想将其转换为$ q.all调用。

It looks something like this. 看起来像这样。

ds.saveData(data).then(function (result1){
    someOtherVar = result1.Id;
    ds.saveSomethingDependant(someOtherData).then(function (result2){
        ds.saveAThirdThing(someOtherVar).then(function (result3){
            ns.notify();
        }, function (error){
            ns.error(error);
        });
    }, function (error){
        ns.error(error);
    });
}, function (error) {
    ns.error(error);
});

Wow what a mess. 哇,真是一团糟。 My concern is where I edit someOtherVar. 我关心的是在哪里编辑someOtherVar。 Is there some other way to do this so I don't have nested promises but still edit data after one promise? 还有其他方法可以使我没有嵌套的Promise,但在一个Promise之后仍然可以编辑数据吗? Nested promises are a nightmare to do jasmine tests on. 嵌套的承诺是进行茉莉花测试的噩梦。

Thanks! 谢谢!

Since your result2 has a dependency on result1 , you'll have to wait until the latter's ready before executing the former. 由于您的result2依赖于result1 ,因此您必须等到后者准备好后才能执行前者。 But, you can still use $q.all if the first and third operations aren't dependent on one another: 但是,如果第一个和第三个操作互不依赖,您仍然可以使用$q.all

$q.all({
  saveData: ds.saveData,
  saveAThirdThing: ds.saveAThirdThing
}).then(function(results) {
  /* expect(results).toEqual({
   *   saveData: result1,
   *   saveAThirdThing: result3
   * });
   */
  return saveSomethingDependent(results.saveData.Id);
}).then(function(result2) {
  // all done
  ns.notify();
}, function(error) {
  // something in the chain above failed
  ns.error(error);
});

We're taking advantage of the fact that you can return a promise from a resolve handler, which will then resolve that promise before sending it to the next promise in the chain (and thereby avoiding nesting). 我们利用了您可以从解析处理程序中返回承诺的事实,该承诺将在将承诺发送到链中的下一个承诺之前解析该承诺(从而避免嵌套)。

You can also simplify somewhat by putting your reject handler at the end of the chain, since you're handling all errors in the same way in your example. 您还可以通过将拒绝处理程序放在链的末尾来进行某种程度的简化,因为在示例中,您以相同的方式处理所有错误。

let's say easy and readable method chain 假设简单易读的方法链

var saveDate = function(data) {
  return ds.saveDate(data);
}

var saveOtherthings = function(result) {
  return $q.all([ds.saveSomethingDependant(result.id), ds.saveAThirdThing(result.id)])

}

saveDate(data)
  .then(saveOtherthings)
  .then(function(result) {
    ns.notify();
  }, function(error) {
    ns.error(error);
  });

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

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