Angular's use of ES6 generator functions allows for easier management of

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?

Answer №1

One possible reason could be that the spawn method is utilizing native Promises instead of the Angular implementation. Consider using $q instead:

function continuer(verb, arg) {
    var result;
    try {
        result = generator[verb](arg);
    } catch (err) {
        return $q.reject(err);
    }
    if (result.done) {
        return result.value;
    } else {
        return $q.resolve(result.value).then(onFulfilled, onRejected);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing a sequence of jQuery's $.when().then() functions

I am facing challenges in understanding how to properly sequence my functions, especially in relation to the $.when() method. function y() { defer = $.Deferred(); $.when(defer).then(console.log(defer.state())); } y(); <script src="https://ajax.go ...

The problem arises when trying to use the Jquery click event on buttons that have been generated

I've encountered an issue where I can create components dynamically, but the click event doesn't seem to work on buttons that are dynamically generated. Check out the code snippet below: HTML file: <div class="merge_sections">&l ...

Error encountered while trying to display the react-bootstrap table

I am having trouble rendering sample data using react-bootstrap tables. Every time I try, I encounter the error: TypeError: Cannot read property 'filter' of undefined I've searched on various platforms and visited multiple links, but I ca ...

The router should display a component based on the user's access level, even if they are

I'm working on a scenario where the home route needs to cater to both admin and user roles. Is there a way to dynamically display the UserComponent if logged in as a user, and show the AdminComponent if logged in as an admin? This is my current setup ...

"Contrasting the initialization of state in the constructor with managing state

Can you explain the distinction between these two methods of initializing state in ES6 other than their access to props? constructor(props) { super(props); this.state = { highlighted: 5, backgroundColor: '#f3f3f3', ...

How can we refresh an updatePanel on the main page from a popup using ASP.Net?

Looking for assistance, thank you in advance. I have two aspx pages - the first one is the main page with an updatepanel where I call the second page as a popup. I am looking for a way to update the updatepanel on the main page from the popup. Thank you f ...

Instead of just redirecting to the page, consider using Express to send the page as data to the success callback of an Angular $

Once the user has been validated, the client will receive the contents of home.html in the result variable instead of being redirected to the home.html page. Client-side request: $http({ method: "post", url: "http://localhost:2222/validateUser", data: { ...

custom dialog box appears using ajax after successful action

Recently, I created a custom dialog/modal box with the following code: <div id="customdialog" class="modal"> <div class="modal__overlay"></div> <div class="modal__content"> <h2><strong>Hello</strong&g ...

Encountering a glitch while trying to utilize History.js

I've decided to incorporate History.js into my web application to address the lack of support for history.pushState() in Internet Explorer. After reviewing various demos and tutorials, I have written this code snippet: var historyJs = window.History; ...

Advantages and disadvantages of distinct methods for looping through HTML elements

My JS code generates HTML elements that are structured like this: <div id="container"> <div id="block_1" class="blocks"></div> <div id="block_2" class="blocks"></div> <div id="block_3" class="blocks"></di ...

How can I address the issue of an inner content scroll bar?

I am facing an issue with the scroll bar on inner content. When I hover over an arrow on the inner content, the scroll bar appears as desired. However, it changes the content in a way that looks odd. Is there a solution to have a scroll bar on the inner co ...

What are some potential causes of webpack-dev-server's hot reload feature not working properly?

Having an issue with my React project. When I try to use hot reload by running "npm start" or "yarn start" with webpack-dev-server configured (--hot flag), I'm getting the error message: [error message here]. Can anyone assist me in troubleshooting th ...

I am interested in retrieving all users along with the places they have created using virtual population

const fetchAllUsers = async (request, response) => { try { await User.find({}).populate('place').exec(function(err, data) { console.log(data.places) console.log(data) res.json(&quo ...

"Trouble with Express.js: CSS isn't loading, yet HTML displays

Click here to view folders and files server.js is the code I have created so far //importing packages const express = require('express'); const admin = require('firebase-admin'); const bcrypt = require('bcrypt'); const path = ...

Issue with accessing $index.$parent in function parameter within ng-repeat in AngularJS

Can anyone with more experience please explain to me why this particular code compiles successfully: <li class="btn dropdown top-stack breadcrumb-btn" ng-repeat="nodeName in selectedNodeNames"> <a class="dropdown-toggle btn-anchor"> ...

Looping through an array

I have created an array as shown below: iArray = [true, true, false, false, false, false, false, false, true, true, true, false, true, false, false, false, false, true] Condition check: If any value in this array is false, I will display an error messag ...

Navigating the complexities of integrating Rollup, ES modules, TypeScript, and JSX can be a challenging endeavor due to

Lately, I've been learning about the tools mentioned in the title. However, I've encountered some bumps along the way, so I'm turning to StackOverflow for help. My Requirements I need something like Rollup to pack my stuff For bare module ...

Converting objects to arrays in Typescript: A step-by-step guide

Can anyone assist me in converting a string to a Typescript array? Any help would be greatly appreciated. Take a look at the following code snippet: private validateEmptyOption(): any { console.log("CHECKED") let isValid = true; this.currentF ...

Encountering an error with the node module timestampnotes: 'command not recognized'

I am encountering an issue while trying to utilize a npm package called timestamp notes. After executing the following commands: $npm install timestampnotes $timestamp I receive the error message: timestamp:126: command not found: slk Subsequently, I ...

AngularJS Accordion Component: A Handy Tool for Organ

I have been trying to implement an Accordion in my angular project by sending HTML structure from a controller. However, despite following the documentation closely, the Accordion is not displaying as expected. Here is a snippet of the code I am using: v ...