UNPKG

1.19 kBJavaScriptView Raw
1'use strict'
2
3function id (e) { return e }
4var prop = require('../util/prop')
5
6module.exports = function asyncMap (map) {
7 if(!map) return id
8 map = prop(map)
9 var busy = false, abortCb, aborted
10 return function (read) {
11 return function next (abort, cb) {
12 if(aborted) return cb(aborted)
13 if(abort) {
14 aborted = abort
15 if(!busy) read(abort, function (err) {
16 //incase the source has already ended normally,
17 //we should pass our own error.
18 cb(abort)
19 })
20 else read(abort, function (err) {
21 //if we are still busy, wait for the mapper to complete.
22 if(busy) abortCb = cb
23 else cb(abort)
24 })
25 }
26 else
27 read(null, function (end, data) {
28 if(end) cb(end)
29 else if(aborted) cb(aborted)
30 else {
31 busy = true
32 map(data, function (err, data) {
33 busy = false
34 if(aborted) {
35 cb(aborted)
36 abortCb && abortCb(aborted)
37 }
38 else if(err) next (err, cb)
39 else cb(null, data)
40 })
41 }
42 })
43 }
44 }
45}
46
47
48
49
50
51
52