Is there any way to cancel all the requests in $q.all()? - angularjs

When a user switch a state when another state is being loaded, I am destroying the controller of the previous state. But there are still some promises in the previous state that are yet to be resolved. So even after destroying the state controller, The then() method of these promises are being called. So I wanted to cancel all the existing promises by calling resolve() on the promises on destroying the controller. But the promise returned by $q.all() does not have a resolve() method. Nor does it return the individual promises on which I can call resolve to abort the promises. Is there any way that I can achieve this?

Related

Use of 'then' in ReactJS

For ease in explaining the significance of 'then', could anyone tell me what is happening in this code?
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
fetchComments returns a promise (probably; it could just be a "thenable"*). A promise is something that will be either resolved or rejected at a later point in time (typically**). then is used to hook up a handler that will be called when the promise is resolved (and optionally when it's rejected, if you pass a second function into then; otherwise you'd use catch).
In this case, that code says that when/if the promise returned by fetchComments resolves, use the resolution value to set the state of the React component using the comments property of that resolution value.
More about promises in this MDN article and in the Promises/A+ spec.
* See the Promises/A+ spec for what a "thenable" is.
** If you use then on a promise that's already resolved or rejected, you're guaranteed by the native promises in JavaScript that your handler will still be called asynchronously. That wasn't always the case with some early promise-like implementations, which would either call your callback asynchronously (if the promise wasn't already settled) or synchronously (if it was), which was...chaotic and unhelpful. JavaScript's native promises and any really good promise library guarantees consistent callback behavior.
I am answering this question bit late but may be helpful to someone at some time.
Let's Start:
From the above code you pasted, I can give you a hint that whenever you see a keyword then in any Javascript code snippet, that is an asynchronous function using promise.
Promise: are objects which store information about whether or not those events have happened yet, and if they have, what their outcome is.Usually, promise will handle success (a.k.a resolve in js code) and failure(a.k.a reject in js code) and also both. So when we create any async functions, the promise is created inside these async functions.
Promise.then: then allows us to assign event handlers to a promise. Depending on the arguments we supply, we can handle success, failure, or both and the return of then is also a promise which means it can handle more events.
And finally to get to the code above, fetchComments is a promise which is an async function, and when the response is resolve it is updating the state of the comments and additionally here we can also handle error scenarios using .catch or even by adding another then
and to end, below link has a nice explanation:
A nice tutorial on Promise and then in javascript is here
Function fetchComments 'll fetch Data and return one Promise then give them to state comments :). But I think you should read here^^.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

what does the term 'Promise-based Http client' mean?

While going through the Redux middleware, I have come across Axios which is 'Promise-based HTTP client' to make Ajax request from browser. Could any body explain about this term and some info about axios?
Before Promise's comes into the picture there is something called Callback to handle asynchronous calls/code. But the main issue with callback is that when it gets nested and more nested it becomes very messy code and harder to understand even for the writer of the code.
To make it bit cleaner Promise comes into the picture which is cleaner in nature, Avoid callback hell problem in nodejs programming.
Moreover the concept async/await is also best fit with the promise instead of callback.
Hope you understand now. Comment below in case of any doubt.
From MDN:
A Promise is a proxy for a value not necessarily known when the
promise is created. It allows you to associate handlers with an
asynchronous action's eventual success value or failure reason. This
lets asynchronous methods return values like synchronous methods:
instead of immediately returning the final value, the asynchronous
method returns a promise to supply the value at some point in the
future.
A Promise is in one of these states:
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
A promise-based client returns promises rather than accepting callbacks.

How to execute onEnter after the onExit api call callback

I call an API on every OnEnter to retrieve the state of my data.
The state of the data is updated on every OnExit by calling a POST on API.
So the test of my state is always late from one state, because the call on the API to retrieve data is called before the save on the State from the onExit.
My question is how to run OnEnter from the OnExit api call callback ?
Thanks
Save the onExit promise and chain the onEnter from it.
var promise = restangularAPI.post();
promise.then ( function () {
restangularAPI.get();
});
If the post has already completed the get will execute immediately. Otherwise the $q service will wait for the post to complete before executing the get.

Why digest cycle does not get called automatically for promise in unit test?

it("should update code when the key is changed through selector", function () {
var Code = "123";
var expectedCode;
service.updateCode(Code).then(function (expectedCode) {
expectedCode = expectedCode;
});
// promises are resolved/dispatched only on next $digest cycle
$rootScope.$apply();
expect(expectedCode).toEqual(`enter code here`Code);
});
Why we need to call $rootScope.apply() explicitly?
Promises are resolved/rejected during the digest cycle which can be triggered by you by calling $rootScope.$apply() or even $rootScope.$digest.
So basically by calling that you are telling angular to process the handlers for the promises that you've resolved/rejected in order to evaluate the results for testing.
When your application is running the digest loop is evaluated automatically for things that happen with the scope of your angular application, so you do not need to call this directly within your application for most cases.
Because then it would be a lot harder to test. I know this may sound counter-intuitive, but once you get a little bit into promise testing you'll understand what I mean.
It would be a pain to expect() stuff from promises, because you would always run into race-conditions. In your example if you omit the $apply(), due to the async nature of promises, the expect would probably be called before the promise is resolve.
So by manually having to $apply/$digest it basically changes your async stuff into a synchronous.

What are Angularjs promise states?

beside success, error and then, do $http get rest promise offer more states we can act upon ?
I once logged in the console a raw response that showed these 3 states and more, but don't remember which.
the $http service extends on the $q service. The $http has 2 additional methods (success, and error) on top of the existing methods provided by $q (given below):
.then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.
This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.
.catch(errorCallback) – shorthand for promise.then(null, errorCallback)
.finally(callback) – allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.

Resources