简体   繁体   English

在angularjs中使用promise

[英]using promise in angularjs

i am new to angularjs and i am learning promise in angular. 我是angularjs的新手,我正在学习angular的promise。 I made a simple sample to understand how the promise works 我做了一个简单的样本来了解诺言如何运作

<body ng-controller="sampleController">
  <div>{{one}}</div>
  <br/>
  <br/>
  <div>Status - {{two}}</div>
  <br/>
  <br/> 
  <div ng-click="callback()">click</div>
</body>

<script>
  function sampleController($scope, $q, $timeout) {
    $scope.one = "Hello World"
    $scope.two = "NA"

    $scope.callback = function() {

      $timeout(function() {
        $scope.one = "Good Evening"
      }, 2000);
    }

    change = function() {
      $scope.two = "Changed"
    }

    var defer = $q.defer()
    var promise = defer.promise;

    promise = promise.then($scope.callback()).then(change());
  }
</script>

JSBin : http://jsbin.com/foxacawa/1/edit JSBin: http//jsbin.com/foxacawa/1/edit

By using the promise, i trying to change the status once the Hello world changes to Good Evening but i am not getting the output. 通过使用Promise,一旦Hello World更改为Good Evening,我尝试更改状态,但是我没有得到输出。 what the right approach? 正确的方法是什么? Please suggest 请建议

the then() callback will be called once the defer is resolved. 一旦延迟解决,将调用then()回调。 To resolve the defer, simply use defer.resolve() (or defer.reject() to show failure) 要解决延迟问题,只需使用defer.resolve() (或defer.reject()显示失败)

I think that's what you might be looking for: 我认为这就是您要寻找的东西:

var defer = $q.defer()

$scope.callback = function(){ 

  $timeout(function() {
    $scope.one = "Good Evening";
    defer.resolve('changed');
  }, 2000);    
}

just check the docs for $q for more details. 只需查看$ q的文档即可了解更多详细信息。

Additionally: with 另外:与

promise = promise.then($scope.callback()).then(change());

you're immediately invoking the $scope.callback and change functions and not of when the promise gets resolved. 您会立即调用$ scope.callback和change函数,而不是调用promise时。

Try 尝试

promise = promise.then($scope.callback).then(change);

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

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