enQue.js
Chain asynchronous functions in succession, consuming the same data stream.
const enQue = new require('enQue')
const myQue = enQue([fn1, fn2, fn3, fn4, fn5])
myQue.run(data)
For full documentation see the enQue source code.
Features
1.) Skip ahead in the que next(4)
would skip to position 4.
2.) Go backwards in the que next(-4)
would go back 4.
3.) Inject a Promise
at a particular que index next({inject:4,promise:Promise})
.
4.) Quit after at specified index next({quit:4}
quits after 4 more iterations.
5.) Allows removing functions by index, variable name, or raw text.
6.) A fill method for convenience.
The above code snippet illustrates how simple it would be to execute 5 asynchronous functions in succession that all operate on the same data. Just make sure each function calls next()
to proceed or next(0)
to quit early.
Since a promise is returned it is always best to attach a .then()
and .catch()
so the above code would become.
myQue.run()
.then(sucessCallback)
.catch(errorCallback)
Instalation
npm install enque
Dependencies
None.
Usage examples
Que = require('enQue')
que = new Que()
function fn1(data, next) {
console.log(1)
next()
}
function fn2(data, next) {
console.log(2)
next()
}
que.add(fn1)
que.run()
que.clear()
que.add([fn1, fn1, fn1])
que.run()
que.clear()
que.fill(fn1, 7)
que.run()
que.clear()
que.add([fn1, fn1, fn1])
que.remove(fn1)
que.run()
que.add([fn1, fn2, fn2, fn2])
que.remove([fn1, fn2], 3)
que.run()
que.clear()
que.add([(d,n)=>n(5), fn1, fn1, fn1, fn1, fn1, fn1])
que.run()
que.clear()
que.add([(d,n)=>n({quit:3}), fn1, fn1, fn1, fn2, fn2, fn2])
que.run()
que.clear()
que.add((d,n,i)=>{console.log("hi"); n()})
que.remove('(d,n,i)=>{console.log("hi"); n()}')
que.run()
fn5 = (data, next, index, done) => {
console.log(index)
index === 2 ? next(0) : next()
}
que.add([fn5, fn5, fn5, fn5, fn5])
que.run()
que.clear()
fn3 = (data, next) => {
data.data = "SEVEN";
next();
}
que.add([(d,n)=>n({inject:5, function: function(d){d.data="7"}}), fn3, fn3, fn3, fn3, fn3])
que.run().then(res=>console.log(res))
que.clear()
Executing the above code as is gives:
1
1
1
1
1
1
1
1
1
1
1
2
1
1
1
1
0
1
2
{ data: '7' }
More examples
const Que = require('enQue');
const que = new Que();
var once = true;
que.add((data, next, done, index) => {
setTimeout(()=>{
data.msg += ' ONE';
next({inject:1, promise: new Promise(s=>{data.msg += " ONE AND A HALF"; s(data)})});
}, 9000)
});
que.add((data, next) => {
setTimeout(()=>{
data.msg += ' TWO';
next();
}, 4000)
});
que.add((data, next) => {
data.msg += ' THREE';
next()
});
function myFn1(data, next) {
data.msg += ' FOUR';
if(once) { once = false; next(-2); }
else next(1);
}
function myFn2(data, next) {
data.msg += ' FIVE';
next();
}
que.add([myFn1, myFn2])
que.run({msg: 'ZERO'})
.then(res => console.log(res.msg))
.catch(err => console.log('Woopsie! ' + err))
Executing the above code as is gives:
ONE ONE AND A HALF TWO THREE FOUR TWO THREE FOUR FIVE