【问题标题】:show a message on timeout, for only two seconds显示超时消息,仅持续两秒钟
【发布时间】:2016-09-22 06:31:35
【问题描述】:

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

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

我的困境是我只想将这条消息本身显示两秒钟。我尝试了以下方法,它奏效了,它是“嵌套”超时的反模式吗?

$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)

【问题讨论】:

    标签: javascript angularjs timeout promise


    【解决方案1】:

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

    这种承诺链

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

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

    【讨论】:

    • 我正在用更新后的答案编辑我的帖子……它应该是这样的吗?我也很困惑,怎么会先运行外部超时,然后运行内部?
    • 是的,应该是这样的。执行顺序与setTimeout 相同。超时回调函数在延迟时间过去后触发,而不是提前一毫秒。
    • 我明白了。在包含内部超时的外部超时上链接 .then 不是更好吗?
    • 并非如此。过多的thenanother antipatternthen 仅在链中出现第三个承诺时出现:$timeout(() => { return $timeout(() => { ... }, 2000) }, 5000).then(() => $timeout(() => { ... }, 1000))
    猜你喜欢
    • 2021-10-11
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多