[英]Using yield with Angular (ES6)
我正在玩ES6,並試圖讓yield
適應角度要求。 var data = yield getData();
無法按我預期的方式工作。 我正在獲取{"value":{"$$state":{"status":0}},"done":false}
並且我想獲取{"value":"its working!","done":true}
這是我的代碼。
<!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>
{"myData": "its working!"}
{"value":{"$$state":{"status":0}},"done":false}
{"value":2,"done":false}
{"value":3,"done":false}
{"done":true}
還要感謝一些解釋!
你做錯了。 實際上,ES6生成器不是一次返回(屈服)某些值,而是每個需求返回一個。 他們不會等到您的諾言得到解決。 如果要使用生成器以同步方式進行異步操作,則必須將代碼包裝到一些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());
})();
您可以在以下位置找到co
實現:
以此類推(在某些實現中,您不需要立即執行它)
另請參閱此問題的答案以了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.