when-traverse
Asynchronously traverse tree of mixed promises and values
Why
Consider this function as Promise.map
+ Promise.all
for trees.
Often enough, we have tree structures, and when we want to transform them asynchronously, we have no other options but use sync variants of functions or write ugly hacks by collecting arrays of inner promises, handling them with Promise.all
, collecting new promises (if there are), waiting for them with Promise.all
again and do a lot of other silly stuff.
This function allows you to wait for tree of mixed promises and simple values, replace some nodes with asynchronous content, remove nodes depending on asynchronous conditions etc.
It handles each node as soon as it becomes available for processing, thus resulting in low overall latency.
Dependencies
Function assumes that DOM API compliant Promise
exists in global namespace (true for latest versions of Chrome and Firefox).
If it's not, for AMD and Node.js polyfill will be loaded and used.
Install
Use with AMD, Node.js or simple <script src>
.
Usage
Let's assume you have following asynchronous tree:
// delayed promise helper (for example only) { return { ; };} // sample tree with nested simple and promised nodesvar tree = a: 1 b: c: d: shouldNotGoHere: ;
Then you can process it as follows:
;
or
// custom visit() function, you can process node and call this.into(node);
or
// no changes, only waiting for all the promises in tree;
enter
and leave
you can return either:
From both - nothing (so this node object will be left intouched);
- new node to replace old one with;
whenTraverse.SKIP
to skip further processing of this node and children (useful inenter
when you don't want to wait for children transformations nor get this node inleave
);whenTraverse.REMOVE
to remove this node in parent;Promise
of anything listed above.
Check out test.js for more code.
License
MIT © Ingvar Stepanyan