Installation
npm install promise-accum
Motivation
Often when using promises, variable scoping becomes an issue, specifically when doing an operation that requires something along the lines of "load two things in the database, then do something based on that".
There are a few ways to solve this problem:
-
Stay in callback hell
; -
Enter variable scoping hell
var item1;; -
Return ugly objects
;
This library provides a solution. Context is stored in a variable called $
. To add the result of a promise to the context, call $('key')
. In this case:
var $ = ; ;
Error handling
Using this solution, the context object must be passed through the entire chain:
;
In most cases, it's as simple as returning $
in the promise. However, in some promise libraries (q and bluebird, among others), errors can be handled by calling .catch(errorHandler)
. This is effectively an alias for .then(null, errorHandler)
– of course, in this case, the context does not get passed through, so any functions after the error handler it.
To mitigate this, promise-accum provides $.passthrough
:
;