What is the difference between $q.race to Promise.race? - javascript

I am using Angularjs version 1.5.7 and $q.race function added in version 1.5.8.
I saw that there is function Promise.race and my question if there is any difference between those functions.
If there is difference should I copy the function from here: AngularJS: $q.race() in old angular versions
and it will works the same like $q.race?
Thanks in advance and sorry for my english!

JavaScript ES6 specifications introduced the method you described above, like Promise.race, Promise.all etc..
The difference is basically that angular has a built-in $q service in order to manage with promises.
This will trigger automatically the digest cycle in order to change everything that could be related to the data returned by the promises or all the involved operations.
If you are allowed to use ES6 specification, you can use directly all the built-in Promises of JavaScript, but then you have to manually trigger the $digest in order to make all the changes happen.
This is one of the main differences between the usage of $q or standard Promises in angularjs.
Moreover, there are a lot of related methods in angular which integrates with $q, like $http for example, and for your tests, you will have your life easier treating directly with $q.
So my suggestion is to use $q if possible.

The core difference is that $q.race will call $rootScope.$apply() under the hood to digest any changes that may occurred after executing your promise callback.
Promise A+ spec has noting to do with that since Promise.all, Promise.race are defined in ES6/ES2015 spec not in Promise A+ spec

Related

Is promise constructor function necessary or can it be avoided?

According to Promise - Javascript | MDN,
The constructor is primarily used to wrap functions that do not
already support promises.
At a low level, the functions that already support promises would
be doing this right i.e constructing a promise using Promise and returning it back?
Is there a better way to create a promise other than using the Promise constructor function?
Eventually, you have to register a callback somewhere right? I mean you can't avoid having a callback that at-least resolves? In other words, we have to wrap it like this somewhere in the library correct?
At the lowest level? Yes, probably.
Depends on the context. If the value you want to resolve the value to is already available, then you'd use Promise.resolve(theValue). If you want to wait for multiple promises you'd use Promise.all(allThePromises). And of course every call to .then returns a new promise.
If you want to do anything with the value of a promise, then yes, you have to pass a callback to .then. There is no other way to get the value.
Having said all that, ES2017 introduced async functions which are basically syntactic sugar for promises. async functions always return a promise and you can use await to unwrap promises. Example:
async function get() {
return await Promise.resolve(42);
}
get().then(console.log);
At a low level, the functions that already support promises would be doing this right i.e constructing a promise using Promise and returning it back?
The eventual goal is that even the low-level APIs within Node.JS will be using the Promise syntax so there will be no need for callbacks. The PromiseJS community considers the constructor syntax to be a polyfill for this eventual behavior. Source.
In practice, this is obviously not the case. Browsers, Node.JS and other Javascript runtime environments make heavy use of callbacks, and so the Promise constructor is used.
Is there a better way to create a promise other than using the Promise constructor function?
Yes- but this depends on application.
Most obviously, if you are using an API which already returns a promise, you can use .then() and .catch() syntax to chain promises together.
There are also a number of libraries which extend the default Promise functionality and provide convenience methods for increased performance and readability. For instance, Bluebird (a common PromiseJS library) offers a way to evaluate the result of multiple promises created concurrently for faster overall runtime.
You can also construct Promises from other paradigms which simplify code- for instance Promise.Promisify which converts a callback function into a Promise one, or Observable.toPromise which converts Observables to promises.
Eventually, you have to register a callback somewhere right? I mean you can't avoid having a callback that at-least resolves? In other words, we have to wrap it like this somewhere in the library correct?
Similar to the answer to your first question, this is a symptom of code currently using the callback paradigm. If all libraries used Promises on a lower level, this wouldn't be the case.
At a low level, the functions that already support promises would be doing this right i.e constructing a promise using Promise and returning it back?
Yes. Maybe. At a low level, we don't know how functions that already support promises do construct those. Imagine what the Promise constructor itself uses to construct promises…
Is there a better way to create a promise other than using the Promise constructor function?
No, there's no other way accessible to JS. But as MDN notes, you should rarely ever need to do this yourself, and rather just use other functions that already create promises for you (which by themselves of course go through the Promise constructor somehow).
Eventually, you have to register a callback somewhere right? I mean you can't avoid having a callback that at-least resolves?
Not necessarily. At a low level, you could also register any arbitrary data structure that allows to resolve a promise, this does not necessarily need to be a callback function. (It is however indeed equivalent in power to registering the resolve callback function).
For example the native implementation of the fetch API (afaik the first native API that directly returns promises) will hardly create JS callback functions anywhere to resolve its promises.

AngularJS $promise used with NgResource

I came across promises as I am going through my journey on learning AngularJS and it has been good so far. Now, I wanted to learn more about using AngularJS optional library resource.js. However, I came across examples that confused me a lot. For example, the promise skeleton is basically like this example.
//post method to server
$http.post('api/school',newStudent).then(fetchStudents).then(function(response){
//do something
}, function(error){
//do something
});
and another example like this assuming we have a List factory
List.save(self.newStudent).$promise.then(fetchStudents).then(function(){
self.newStudent = {};
});
So my question is why the use of $promise? What is the use of it? It was not really explained in the book I am using and I am confuse on when to use it or not. Any clear explanation will be appreciated. Thanks
A service that helps you run functions asynchronously, and use their
return values (or exceptions) when they are done processing
Promises provide a simpler alternative for executing, composing, and managing asynchronous operations when compared to traditional callback-based approaches. They also allow you to handle asynchronous errors using approaches that are similar to synchronous try/catch.
Read more about it at :
https://docs.angularjs.org/api/ng/service/$q
http://haroldrv.com/2015/02/understanding-angularjs-q-service-and-promises/
http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls

RxJS + (async/await) for (multiple-event) use cases

I am writing a Javascript App to get data from sensors. I started using ES6 Promises + Generators using Bluebird and the Bluebird.cororutine in both (client and server), but it didn't work fine.
I was advised that Promises didn't work properly in (multiple-event) use cases, and that an alternative could be RxJS.
I've taken a look to RxJS, and it looks like can do the same as the Promises but even better.
I wanted to use generators (async/await) to write the async code to look as sync, and my question is:
Can I use RxJS + (async/await) or RxJS has already its own way to do the same as (async/await) ?
Thanks
Async/await is not part of ES6, it's scheduled for ES7. So you're probably not going to use it any time soon in JavaScript. TypeScript supports async/await for ES5 since 2.1.
It think you'll be able to use RxJS with async/await when it comes out. Async/await works with Promises, just like RxJS even though it mostly works with Observables. There are methods such as Observable.toPromise() to convert an Observables to Promises and most Observables also accept a Promise as a parameter.
So I think both are going to be well interchangable (I haven't tried thi personally).
If your primary interest is to make you code more readable than RxJS is a good choice to reduce callback hell.
These two examples show how to call multiple HTTP requests in order using Observable.concatMap() operator. Both examples are written in TypeScript but it should be basically the same in
ES6 as well. Also these examples use the new RxJS implementation (https://github.com/ReactiveX/RxJS):
Angular 2 + rxjs - how return stream of objects fetched with several subsequent http requests
How to use exhaustMap in ReactiveX/rxjs 5 in TypeScript

Reactjs promises, how should we use it?

I've been reading a lot about React for the last 3 days, but I don't see much information about the use of promises, so I have that concern.
Is there any library for this?
How should I use promises in React?
React doesn't come with a promise library baked in like Angular with $http. You will have to find your own.
A few you can try:
Bluebird (personal recommendation)
jQuery's $ajax
Native promises (unless you actually have to support IE): http://caniuse.com/#feat=promises
Promise object is used for handling asynchronous computations which has some important guarantees that are difficult to handle with the callback method (the more old-school method of handling asynchronous code).
A Promise object is simply a wrapper around a value that may or may not be known when the object is instantiated and provides a method for handling the value after it is known (also known as resolved) or is unavailable for a failure reason (we'll refer to this as rejected).
Using a Promise object gives us the opportunity to associate functionality for an asynchronous operation's eventual success or failure (for whatever reason). It also allows us to treat these complex scenarios by using synchronous.
To see more at : https://www.npmjs.com/package/react-promise

Protractor and promises

A lot of the functions exposed by Protractor return promises.
Do I need to structure my Jasmine tests using Protractor using things like async tests (with the done parameter), and .then, or does Protractor provide some magic to do this for me?
WebDriverJS takes care of that with the control-flow. Protractor adds the modification of Jasmine's expect to keep the thens at bay. It's best explained here.
Yes, there is some magic that protractor performs in order to wait for each promise to resolve.
The best description of the process is in the protractor documentation: How It Works.
This means we don't have to structure the tests as async using a done. We can simply assert using expect (in Jasmine) and everything should work.

Categories