Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 使用带有角度承诺的if-guard语句的最佳实践_Angularjs - Fatal编程技术网

Angularjs 使用带有角度承诺的if-guard语句的最佳实践

Angularjs 使用带有角度承诺的if-guard语句的最佳实践,angularjs,Angularjs,以下是使用有角度保证的if防护的最佳方法吗 function doIt(p) { var dfd = $q.defer(); if (!p) { // this the best syntax to return the promise? dfd.resolve(true); return dfd.promise; } // whole bunch of code stuff with a resolve() and reject()

以下是使用有角度保证的if防护的最佳方法吗

function doIt(p) {
   var dfd = $q.defer();
   if (!p) {
      // this the best syntax to return the promise?
      dfd.resolve(true);
      return dfd.promise;
   }

   // whole bunch of code stuff with a resolve() and reject()

   // finally
   return dfd.promise;
}

我想这会干净得多

function doIt(p) {
    if (!p)
        return $q.when(true)
    else
        return someLongFunction()
}
或者如果你想说清楚,那是一个守卫

function doIt(p) {
    if (!p)
        return $q.when(true)

    return someLongFunction()
}

当(!p | | someLongFunction())时,它甚至可以
返回$q。哦,是的。那肯定更短。但是作为一种保护子句模式,最好将第一个检查分开,就像在第二个代码块中一样。干杯