2

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!

asked Feb 17, 2015 at 16:55

1 Answer 1

0

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.

answered Feb 17, 2015 at 17:54
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.