【问题标题】:Using yield with Angular (ES6)在 Angular (ES6) 中使用 yield
【发布时间】:2015-04-18 10:57:55
【问题描述】:

我正在使用 ES6 并试图让 yield 处理角度请求。 var data = yield getData(); 没有按照我预期的方式工作。我得到{"value":{"$$state":{"status":0}},"done":false},我想得到{"value":"its working!","done":true}

这是我的代码。

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!"}

结果

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

{"done":true}

也非常感谢您的解释!

【问题讨论】:

    标签: javascript angularjs ecmascript-6 es6-promise


    【解决方案1】:

    你做错了。实际上 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的实现你可以在哪里找到:

    等等(在某些实现中你不需要立即执行它)

    也可以see answers of this question了解更多。

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2015-12-11
      • 2015-08-12
      • 1970-01-01
      • 2019-04-04
      • 2017-11-19
      • 2016-05-04
      • 2016-10-14
      • 1970-01-01
      相关资源
      最近更新 更多