nThen... Do this... nThen... Do that.
nThen is designed to be the most small, simple and intuitive asynchronous library.
How you used to do things
let x = ;let y = ;let a = ; // Hey!let b = ; // these two could run at the same time!let z = ;let c = ;;
Ok so we learned that doing it that way is slow and we have asynchronous so we never have to be slow anymore.
The naive asynchronous approach
That doesn't look like very much fun :( And to make matters worse, what happens if one of those functions never returns?
var to = ;
You can see where this is going.
nThen to the rescue
nThen allows you to do things in parallel by putting them in blocks and one block will not execute until all of the callbacks from the previous one have completed.
How do we know when all callbacks have been completed ? You wrap them using the waitFor function wrapper. Waitfor wraps a function, so the result of waitFor is another function and when that is called, all arguments are passed through to the function which was given to waitFor, however, nThen will block until all waitFors have been called.
You can use waitFor as many times as you want in an nThen block, you can even use a waitFor invocation inside of another waitFor invocation and it will keep the nThen block from terminating.
For example this works:
const nThen = ;const Fs = ;;
Using nThen to sequencialize a list of async operations
Sometimes you want to do a variable number of things in sequence. Suppose you wanted to stat every file in the /dev directory but you want to do them one at a time.
You can loop over all files using nThen to access each one sequencially like this:
const nThen = ;const Fs = ;var nt = nThen;Fs;
You can use multiple levels of nesting of nThen, for example you might use a loop of async operations inside of one block of larger nThen chain, like this. Notice waitFor can be used without a wrapped function.
const nThen = ;const Fs = ;let fileList;;
You can end your nThen chain with an orTimeout call which will abort the execution of the nThen chain if the execution takes more than a given number of milliseconds.
const nThen = ;;
- If you do not call waitFor at all within an nThen block, the block will exit synchronously
- You can use waitFor without wrapping any callback function, it works fine with nothing
- nThen is fully ECMA-5 compatible, it is also compatible with flow typing system
- nThen does operations in sequence (no parallelism), if you'd like to do n parallel operations check out saferphore
Public Domain or MIT license, as you wish.