简体   繁体   English

使用重定向到承诺链

[英]Using redirections into promises chain

I'm using promises to call a serie of webservices, but I'd like, in some cases, use redirection in the middle of my logic.我正在使用 Promise 来调用一系列网络服务,但在某些情况下,我希望在我的逻辑中间使用重定向。 The problem is that the promises chain continue to execute after the redirection occured.问题是在重定向发生后,promise 链会继续执行。

Here is the code:这是代码:

myfunc = function() {
  return PromiseCall1()

  .then(function(data){
    if (condition){
      $location.path(some_url); // This is a redirection with AngularJS

    } else {
      return PromiseCall2();
    }
  })

  .then(function(data){
    return PromiseCall3();
  })

  .then(function(data){
    // Some other stuff here
  })

};

The expected behaviour would be:预期的行为是:

  • PromiseCall1() must be called PromiseCall1()必须被调用
  • if condition is true, no other promise must be called, just do the redirection如果condition为真,则不必调用其他承诺,只需进行重定向
  • if condition is false, Promise2 then Promise3 must be called.如果condition为假,则必须调用 Promise2 然后 Promise3。

How would you do it?你会怎么做? Thank you for your help.感谢您的帮助。

func = function () {
    return PromiseCall1().then(function (data) {
        if (condition) {
            $location.path(some_url); // This is a redirection with AngularJS
        } else {
            return PromiseCall2().then(function (data) {
                return PromiseCall3();
            }).then(function (data) {
                // Some other stuff here
            });
        }
    });
};

Petka's solution is ok. Petka的解决方案是可以的。 If you want.如果你想。 It is possible if you wrap your then handlers with Maybe.如果你用 Maybe 包装你的 then 处理程序,这是可能的。

Something like:就像是:

var maybe = function(fn){
     return function(value){
          if(value === maybe.Nothing) return maybe.Nothing;
          return fn.apply(this,arguments);
     };
});
maybe.Nothing = {}; // unique reference

Which would let you do哪个会让你做

Promise.try(function(){
    return 15;
}).then(maybe(function(val){
    console.log("got",val);    
    return maybe.Nothing;
})).then(maybe(function(val){
    console.log("This never gets called");  
}));

This gives you an explicit value hook to signal not continuing any promise in the chain that is wrapped with a maybe.这为您提供了一个显式的值挂钩,以表示不会继续在用 may 包裹的链中的任何承诺。

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

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