5

I'm replacing $http with Fetch API and got replaced $q with Promise API. Because of that, Angular didn't run digest cycles anymore, thus UI didn't render. To solve this problem I tried Zone.js and that seems to solve our problems partially. Unfortunately its API completely changed in 0.6 so we're using legacy 0.5.15.

Now to the actual problem.

When refreshing the page Angular configs and bootstraps the application like expected. In this phase I'm initializing the Zone and decorating the $rootScope.apply with the Zone and $rootScope.$digest(). Now when I transition between states/routes (with ui-router) everything works as expected, but when full refreshing there's a race condition and the zone/digest doesn't run correctly. I'm not sure how to fix it.

I have the following code in a angular.run() block:

console.log('Zone setup begin');
const scopePrototype = $rootScope.constructor.prototype;
const originalApply = scopePrototype.$apply;
const zoneOptions = {
    afterTask: function afterTask() {
        try {
            $rootScope.$digest();
        } catch (e) {
            $exceptionHandler(e);
            throw e;
        }
    }
};

scopePrototype.$apply = function $applyFn() : void {
    const scope = this;
    const applyArgs = arguments;

    window.zone.fork(zoneOptions).run(() => {
        originalApply.apply(scope, applyArgs);
        console.log('Zone + $digest run!');
    });
};
console.log('Zone setup end');

Above you can see that I log to the console when the Zone initialization begins, when it ends and when it's run (+ Angular digest cycle). In my controller where I fetch the data via Fetch API I've added a console.log('Data fetched!'); so I know when the data has been fetched.

Now the output in console:

State transition with ui-router (works perfectly)

Notice that the digest is run in the end.

Zone setup begin
Zone setup end
Zone + $digest run!
Zone + $digest run!
Zone + $digest run!
Zone + $digest run!
Data fetched!
Zone + $digest run!

Full refresh on state/route (doesn't run in the end)

Zone setup begin
Zone setup end
Zone + $digest run!
Zone + $digest run!
Zone + $digest run!
Zone + $digest run!
Data fetched!

As you can see the Zone/digest doesn't run after the data is fetched, which is why the data and UI isn't rendered on the page.

8
  • The question doesn't contain a plunk or something that could help to debug the problem, which is a must here. $apply patch looks really fishy. What was the reason for switching from $q and $http to native promises and Fetch? You efficiently eliminate a bunch of benefits of Angular as a framework and create of bunch of problems instead. Doesn't look like a good trade-off. Commented Aug 22, 2017 at 22:25
  • That's because I'm not able to reproduce this. The reason for switching from $q and $http to native promises and Fetch was because the end-goal is to replace Angular with React. ui-router (which we are using for routing) now supports routing to React components. Commented Aug 22, 2017 at 23:34
  • I see. Generally I would suggest to avoid implicit digests because they will result in uncontrollable mess with poor performance. A reasonable intermediate solution would be to create a service that wraps fetch result with $q promise (good for testing, too). You can also check another approach that addresses native promises in A1 in general, stackoverflow.com/questions/39943937/… Commented Aug 23, 2017 at 0:31
  • 1
    $q is returned from inside async function. It won't work like that. You can check that returned promise is still instanceof Promise. This doesn't mean that it's the issue you're having but it's definitely a problem. Btw, you should never rely on older Zone, the whole point of Zone is that it's constantly fixed because it's one huge hack. Commented Aug 23, 2017 at 0:51
  • 1
    Indeed, but this is not how async/await works. The easiest way to avoid this is to not use async function here. Commented Aug 23, 2017 at 1:04

2 Answers 2

2

Convert the ES6 promises created by the fetch API to AngularJS $q promises with $q.when.

Use $q.when to convert ES6 promises to AngularJS promises1

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc...2 Since the promise comes from outside the AngularJS framework, the framework is unaware of changes to the model and does not update the DOM.

Use $q.when to convert the external promise to an Angular framework promise:

var myRequest = new Request('flowers.jpg');

$q.when(fetch(myRequest)).then(function(response) {
    //code here
})

Use $q Service promises that are properly integrated with the AngularJS framework and its digest cycle.

$q.when

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

-- AngularJS $q Service API Reference - $q.when

Sign up to request clarification or add additional context in comments.

4 Comments

I understand, but I would like to seperate this From Angular as much as possible because the end-goal is to replace Angular. I've refactored all controllers and services to pure ES6 and utilising 1.5 components. However, as you saw above I'm using Zone.js to achieve this and it works, but for some odd reason it doesn't run the last digest loop in the end after fetching the data.
I tried wrapping the Fetch Promise in $q.when() but it behaved exactly the same.
As @estus stated, returning a $q promise to the .then method of an ES6 promise returns a new ES6 promise. Conversely, the .then method if a $q promise returns a new $q promise. Only scope changes in the .then of a $q promise are applied in the AngularJS execution context.
So the only way is to go back to $http. There must be some way to monkey patch or something?
1

Rationale

Wrapping $q.when will work but in my team's experience it will be very finicky and prone to error. As one example, returning $q.when from inside the body of a Promise.then function will still chain as a regular Promise and you won't get a $digest on callbacks.

It also requires all authors to understand the difference between two very similar looking constructs (Promise/$q) and care about their concrete types for every level of an asynchronous call. If you are using modern conveniences like async/await (which abstracts the Promise types further), you're gonna be in even more trouble. Suddenly none of your code can be framework agnostic.

Our team decided it was worth committing a big monkey patch to ensure all the promises (and the async/await keywords) "just worked" without needing additional thinking.

Ugly? Yes. But we felt it was an okay tradeoff.


Patch Promise callbacks to always apply $rootScope

First we install the patch against Promise in a angular.run block:

angular.module(...).run(normalizePromiseSideEffects);

normalizePromiseSideEffects.$inject = ['$rootScope'];

function normalizePromiseSideEffects($rootScope) {
  attachScopeApplicationToPromiseMethod('then');
  attachScopeApplicationToPromiseMethod('catch');
  attachScopeApplicationToPromiseMethod('finally');

  function attachScopeApplicationToPromiseMethod(methodName) {
    const NativePromiseAPI = window.Promise;
    const nativeImplementation = NativePromiseAPI.prototype[methodName];

    NativePromiseAPI.prototype[methodName] = function(...promiseArgs) {
      const newPromiseArgs = promiseArgs.map(wrapFunctionInScopeApplication);
      return nativeImplementation.bind(this)(...newPromiseArgs);
    };
  }

  function wrapFunctionInScopeApplication(fn) {
    if (!isFunction(fn) || fn.isScopeApplicationWrapped) {
      return fn;
    }

    const wrappedFn = (...args) => {
      const result = fn(...args);
      // this API is used since it's $q was using in AngularJS src
      $rootScope.$evalAsync();
      return result;
    };
    wrappedFn.isScopeApplicationWrapped = true;
    return wrappedFn;
  }
}

Async/Await

If you want to support the use of async/await, you'll also need to configure Babel to always implement the syntax as Promises. We used babel-plugin-transform-async-to-promises.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.