在超时时显示一条消息,仅持续两秒钟

时间:2016-05-24 21:01:41

标签: javascript angularjs timeout promise

我有以下代码,如果承诺在五秒钟后没有返回,则会显示一条消息:

$timeout(function () {
        if (!$scope.promiseComplete && $scope.submitted) {
          $scope.message = {
            content: [{
              title: '',
              msg: 'Service down - created'
            }],
            type: 'error'
          };
          return;
        }
      }, 5000)

我的困境是我只想在两秒钟内显示这条信息。我尝试了以下它并且它起作用了,它是一种反模式,以及#34; nest"超时?

$timeout(function () {
        if (!$scope.promiseComplete && $scope.submitted) {
          $scope.message = {
            content: [{
              title: '',
              msg: 'Service down -  Railcar ASN created'
            }],
            type: 'error'
          };
          $timeout(function(){
            $scope.message = null;
          }, 2000)
          return;
        }

      }, 5000)

更新:基于这里的回答是我的目的:

 $timeout(function () {
        if (!$scope.promiseComplete && $scope.submitted) {
          $scope.message = {
            content: [{
              title: '',
              msg: 'Service down -  created'
            }],
            type: 'error'
          };
          return $timeout(function(){
            $scope.message = null;
          }, 2000)
        }
      }, 5000)

1 个答案:

答案 0 :(得分:1)

$timeout是基于承诺的,它返回一个可以链接的承诺。是的,嵌套的$timeout或任何其他承诺may be an antipattern

这种承诺链

  $timeout(function () {
    if (!$scope.promiseComplete && $scope.submitted) {
      ...
      return $timeout(function(){
        $scope.message = null;
      }, 2000)
    }
  }, 5000)

保证嵌套的级别不超过2级,并且可以使用top $timeout返回的promise,整个promise链可以扩展或测试。

相关问题