带有$ http服务的ES6 Generator

时间:2016-03-09 22:01:54

标签: javascript angularjs

我尝试使用Angular $ http服务在客户端使用ES6生成器。如果可能的话,我希望能够在不使用回调的情况下使用$ http服务。像:

var gen = function* () {
    var test = yield $http.get('/test/');
    console.log(test);
};

var http = gen();
http.next();
http.next(); // returns undefined

/// or ///

var gen = function* () {
    yield $http.get('/test/');
};
console.log(http.next()); //returns a promise object which won't allow me to use the needed data

我问的原因是因为我试图模仿这个演示https://youtu.be/QO07THdLWQo?t=4m58s

我只是在寻找最简单,最直接的方法。有什么建议吗?

1 个答案:

答案 0 :(得分:-2)

一个可能的选择是将生成器函数包装在Bluebird的Promise.coroutine中,如下所示:

//make sure Bluebird source code is included

Promise.coroutine(function* () {
    var gen = yield $http.get('/test/');
    console.log(gen.data);
})();

这已被证明在更复杂的应用程序中非常有用,我希望其他人也会觉得它很有用。出于这个原因,尽管选票下降,我仍然保持这个问题。以下是有关该主题的有用链接: https://gist.github.com/learncodeacademy/bf04432597334190bef4

相关问题