简体   繁体   English

在Angular(ES6)中使用收益

[英]Using yield with Angular (ES6)

I'm playing around with the ES6 and trying to get yield to work with an angular request. 我正在玩ES6,并试图让yield适应角度要求。 var data = yield getData(); Is not working the way I'm anticipating. 无法按我预期的方式工作。 I'm getting {"value":{"$$state":{"status":0}},"done":false} and I want to get {"value":"its working!","done":true} 我正在获取{"value":{"$$state":{"status":0}},"done":false}并且我想获取{"value":"its working!","done":true}

Here is my code. 这是我的代码。

index.html index.html

<!DOCTYPE html>
<html ng-app="app">
  <body ng-controller="bodyCtrl">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js"></script>
    <script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script>
    <script src="https://google.github.io/traceur-compiler/src/bootstrap.js"></script>
    <script>
        angular.module('app', []);
angular.module('app')
  .controller('bodyCtrl', function ($scope, $http, $q) {
  var getData = function () {
    var deferred = $q.defer();

    $http.get('data.json').then(function (response) {
      console.log(response.data.myData);
      deferred.resolve(response.data.myData);
    });

    return deferred.promise;
  };


  var myGen = function*(){
    var data = yield getData();
    var two = yield 2;
    var three = yield 3;
    console.log(data, two, three);
  };


  var gen = myGen();
  console.log(JSON.stringify(gen.next()));
  console.log(JSON.stringify(gen.next()));
  console.log(JSON.stringify(gen.next()));
  console.log(JSON.stringify(gen.next()));
});
    </script>

  </body>
</html>

data.json data.json

{"myData": "its working!"}

Result 结果

{"value":{"$$state":{"status":0}},"done":false}
{"value":2,"done":false}
{"value":3,"done":false}

{"done":true}

Would really appreciate a little explanation as well! 还要感谢一些解释!

You do it wrong. 你做错了。 Actually ES6 generators just return (yield) some values not at once, but one per demand. 实际上,ES6生成器不是一次返回(屈服)某些值,而是每个需求返回一个。 They will not wait until your promise will be resolved. 他们不会等到您的诺言得到解决。 If you want to use your generator to do asynchronous operation in synchronous fashion you must wrap your code into some co function: 如果要使用生成器以同步方式进行异步操作,则必须将代码包装到一些co函数中:

co(function*() {
    var gen = myGen();
    console.log(yield gen.next());
    console.log(yield gen.next());
    console.log(yield gen.next());
    console.log(yield gen.next());
})();

where co realization you can find in: 您可以在以下位置找到co实现:

and so on (in some realizations you don't need to immediately execute it) 以此类推(在某些实现中,您不需要立即执行它)

Also see answers of this question to understand more. 请参阅此问题的答案以了解更多信息。

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

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