A stateful context to DRY up your promise chain.
Often times, especially in specs, there are times that you have to deal with multiple values in a promise chain.
A Gentle Example
Let's say you are building a Twitter-like application and want to test that following works, that is, when A follows B and B updates a status, A should see B's status in the timeline.
One approach is to nest these promises, resulting in a promise hell instead of a callback hell.
Another approach is to pass all the variables we need in the future steps through the promise chain. Notice how you have to maintain the correct order of values and parameters in each step.
And yet another approach is to just store these variables as local variables. Notice how you have to create multiple variables and assigning them yourself.
var user1 user2 statusPromiseall
With a StatefulContext, this becomes:
And this StatefulContext is implemented using 8 lines of code.
var StatefulContext =var the = set = theset
Use it in your mocha tests
var StatefulContext =
More descriptive name, please
You might think that the name
set are not quite descriptive.
You can also name it like this:
And the above example becomes:
Returns a promise that will resolve when all promises inside the
object are resolved.
Also, the resolved values are added the
context with corresponding key as a side effect.
If any of the promise in the object is rejected, the returned promise will be rejected.
context = new StatefulContext()
Returns a new StatefulContext object.
var the =
This object has a
.set method on it, already bound to the created StatefulContext instance. Therefore, you can store that function in a variable and call it without having to worry about the value of
Equivalent to calling
Warning: Don't call
set with an object with a key called