|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const async = op => { |
| 4 | + switch (op) { |
| 5 | + case 'map': return api.metasync.map; |
| 6 | + case 'filter': return api.metasync.filter; |
| 7 | + case 'reduce': return api.metasync.reduce; |
| 8 | + case 'each': return api.metasync.each; |
| 9 | + case 'series': return api.metasync.series; |
| 10 | + case 'find': return api.metasync.find; |
| 11 | + } |
| 12 | +}; |
| 13 | + |
| 14 | +function ArrayChain(array) { |
| 15 | + this.array = array; |
| 16 | + this.chain = []; |
| 17 | +} |
| 18 | + |
| 19 | +ArrayChain.prototype.execute = function(err) { |
| 20 | + const item = this.chain.shift() || {}; |
| 21 | + if (err) { |
| 22 | + if (!item.op) throw err; |
| 23 | + if (item.op === 'catch') { |
| 24 | + item.fn(err); |
| 25 | + return this.execute(); |
| 26 | + } else { |
| 27 | + return this.execute(err); |
| 28 | + } |
| 29 | + } |
| 30 | + if (!item.op) return; |
| 31 | + if (item.op === 'then') { |
| 32 | + item.fn(this.array); |
| 33 | + return this.execute(); |
| 34 | + } |
| 35 | + const op = async(item.op); |
| 36 | + if (!op) return this.execute(); |
| 37 | + op(this.array, item.fn, (err, data) => { |
| 38 | + if (err) return this.execute(err); |
| 39 | + this.array = data; |
| 40 | + this.execute(); |
| 41 | + }); |
| 42 | +}; |
| 43 | + |
| 44 | +['then', 'catch', 'map', 'filter', 'reduce', 'each', 'series', 'find'] |
| 45 | + .map(op => { |
| 46 | + ArrayChain.prototype[op] = function(fn) { |
| 47 | + this.chain.push({ op, fn }); |
| 48 | + return this; |
| 49 | + }; |
| 50 | + }); |
| 51 | + |
| 52 | +ArrayChain.prototype.fetch = function(fn) { |
| 53 | + this.chain.push({ op: 'then', fn: res => fn(null, res) }); |
| 54 | + this.chain.push({ op: 'catch', fn }); |
| 55 | + this.execute(); |
| 56 | + return this; |
| 57 | +}; |
| 58 | + |
| 59 | +module.exports = { |
| 60 | + for: array => new ArrayChain(array) |
| 61 | +}; |
0 commit comments