Promises are fulfilled (resolved or rejected) with a single value. If we need to keep
track of multiple values we can return several values as an array,
even using .spread
method for convenience
1 | promise |
Passing multiple values using separate arguments quickly becomes cumbersome. Some promise implementation,
for example AngularJS $q do not implement .spread
method, forcing to use an array argument
1 | $qPromise |
We can use a helper method that takes a function expecting separate arguments and create new function that splits an array.
1 | function spread(fn) { |
Even when .spread
method is available, passing all values through every function is inconvenient.
We might generate a value Z at the step N and use it only at the step N + K. It would be nice to avoid
passing the value Z through functions at steps N + 1 through N + K - 1.
I use a separate object for this. Since the promise chain is usually constructed inside a function, the separate object is a local variable scoped to the function.
1 | function action() { |
If we want, we could return the full object in the last step of the promise chain.