Why does the prom.join () function execute the function as the last parameter?

Say I have a step in a procedure that requires a search for two objects. I would use join() to coordinate the search:

 return promise.join(retrieveA(), retrieveB()) .spread(function(A, B) { // create something out of A and B }); 

The documentation shows that you can also pass a handler to the last parameter:

 return promise.join(retrieveA(), retrieveB(), function(A, B) { // create something out of A and B }); 

I am curious what the rationale for the existence of this option.

+8
javascript promise bluebird
source share
2 answers

Actual time : the reason .join was to make @spion happy. No wonder using .join means that you have a static and well-known number of promises, which makes it easier to use with TypeScript. Petka (Esailija) liked the idea, as well as the fact that it can be further optimized because it does not need to obey the strange guarantees that another form must adhere to.

Over time, people started (at least I) started using it for other use cases, namely using promises as a proxy.

So, tell us what it does better:

Static analysis

It is difficult to statically analyze Promise.all , since it works with an array with unknown types of promises of potentially different types. Promise.join can be entered, since it can be considered as taking a tuple - for example, for case 3 promises you can give it a signature like (Promise<S>, Promise<U>, Promise<T>, ((S,U,T) -> Promise<K> | K)) -> Promise<K> , which simply cannot be done in a safe way for Promise.all .

proxying

This is very convenient to use when writing promise code in a proxy style:

 var user = getUser(); var comments = user.then(getComments); var related = Promise.join(user, comments, getRelated); Promise.join(user, comments, related, (user, comments, related) => { // use all 3 here }); 

It's faster

Since he does not need to display the value of this promises cache and store all checks .all(...).spread(...) - it will work a little faster.

But ... you, as a rule, do not care.

+9
source share

you can also pass the handler to the last parameter. I am curious what the rationale for the existence of this option.

This is not an "option". This is the sole purpose of the join function.

 Promise.join(promiseA, promiseB, …, function(a, b, …) { … }) 

exactly equivalent

 Promise.all([promiseA, promiseB, …]).spread(function(a, b, …) { … }) 

But, as mentioned in the documentation , he

much easier (and more productive) to use when you have a fixed amount of discrete promises

This eliminates the need to use an array literal, and it does not need to create this intermediate promise object for the result of the array.

+3
source share

All Articles