简体   繁体   中英

Using yield with Angular (ES6)

I'm playing around with the ES6 and trying to get yield to work with an angular request. 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}

Here is my code.

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

{"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. 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(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:

and so on (in some realizations you don't need to immediately execute it)

Also see answers of this question to understand more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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