Recently, I have integrated generators into my Angular project. Here is how I have implemented it so far:
function loadPosts(skip) {
return $rootScope.spawn(function *() {
try {
let promise = yield User.findAll();
$timeout(function () {
// handle the user list
});
} catch (err) {
// handle err
}
});
}
Based on my research, it seems that the next part may not be necessary in es7. Currently, I have the spawn
function set up in the run block of my application.
$rootScope.spawn = function (generatorFunc) {
function continuer(verb, arg) {
var result;
try {
result = generator[verb](arg);
} catch (err) {
return Promise.reject(err);
}
if (result.done) {
return result.value;
} else {
return Promise.resolve(result.value).then(onFulfilled, onRejected);
}
}
var generator = generatorFunc();
var onFulfilled = continuer.bind(continuer, "next");
var onRejected = continuer.bind(continuer, "throw");
return onFulfilled();
};
Everything is functioning properly with my current setup; however, one aspect that bothers me is the need to call $timeout()
after each promise. Without this, my $scope
variables initialized within the timeout are not set. It appears that the manual triggering of the angular digest system is required.
What is the reason for this and is there a cleaner solution available?