javascript - 超时时显示一条消息,仅两秒钟

标签 javascript angularjs timeout promise

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

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

最佳答案

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

这种 promise 链

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

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

关于javascript - 超时时显示一条消息,仅两秒钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37423821/

相关文章:

javascript - Node.js 添加 'semi-dynamic' 内容的最佳方式

javascript - 在 AngularJS 中获取当前 Controller 名称

PHP超时错误处理

javascript - 如何使用javascript获取文本输入中的html特殊字符

javascript - 用一个正则表达式解析复杂的字符串

javascript - 如何使用正则表达式在 angularjs 上打印值?

javascript - AngularJS — Ng 重复数组对象

javascript - setTimeout() 不等待

带有隐藏内容的 jQuery 悬停

javascript - 如何在 node.js 中发送巨大的数据池作为响应?