简体   繁体   English

嵌套的递延Q Promises解决方案可以简化吗?

[英]Can nested deferred Q Promises resolves be simplified?

I have combined some typical (anti-)pattern I have come along, looking at javascript using the Q library : 我结合了一些典型的(反)模式,使用Q库查看javascript:

How much of this can be simplified? 其中有多少可以简化? (or is pointless) Especially: (或毫无意义)特别是:

  • A: What is the value in deferred.resolve(... over returning a value and thus resolving right away? Only the fact, that code that further code get's executed, ie. doSomeMore() ? 答:在deferred.resolve(...返回返回值并立即解决的情况下,值是多少?仅事实是,执行了其他代码的代码,即doSomeMore()
  • if so, for A2 this is pointless in this code? 如果是这样,对于A2来说,这段代码毫无意义吗?
  • B: What is the value in deferred.reject over throw throw new Error('') B: deferred.reject over throw throw new Error('')的值是多少
  • C: The try-catch also irritates me. C:试捕也使我感到恼火。 Only to ensure doSomeMore() ? 仅确保doSomeMore()吗?

    function foo(u) { 函数foo(u){

     var deferred = Q.defer(); bar(u).then( function (v) { if (v==42) { deferred.resolve( Q(null) ); // A } else { try { var controller = new Controller(); deferred.resolve( controller ); // A2 } catch (error) { deferred.reject(error); // B,C } doSomeMore(); } return deferred.promise; }); 

    } }

Yes, the purpose of this code seems to be ensuring that doSomeMore() is executed regardless what happened when the Controller was constructed. 是的,此代码的目的似乎是确保无论构造Controller时发生什么,都执行doSomeMore() You could get that more easily though: 不过,您可以更轻松地获得它:

function foo(u) {
    return bar(u).then(function (v) {
        if (v == 42) {
            return null;
        } else {
            try {
                return new Controller();
            } finally {
                doSomeMore();
            }
        }
    });
}

Something like this maybe? 像这样的东西?

return bar(u).then(function (v) {      
  if (v==42) 
    return null;  
  return new Controller();  
}).finally(function() { doSomeMore(); });

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

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