-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
53 lines (42 loc) · 1013 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
'use strict';
var Queue = require('@mapbox/basic-queue');
var wrappy = require('wrappy');
var slice = Array.prototype.slice;
function asyncOnce(fn) {
// Our state
var _err;
var _result;
var _called = false;
function worker(work, done) {
var ctx = work.ctx;
var initial = work.initial;
var cb = work.cb;
function updateState(err, result) {
_err = err;
_result = result;
_called = true;
cb(_err, _result);
done();
}
if (_called) {
cb(_err, _result);
done();
} else {
fn.apply(ctx, initial.concat(updateState));
}
}
var _queue = new Queue(worker, 1);
return function () {
var args = slice.call(arguments, 0);
var work = {
ctx: this,
initial: args.slice(0, -1),
cb: args.slice(-1)[0],
};
if (typeof work.cb !== 'function') {
throw new Error('async-once only works with node-style async functions');
}
_queue.add(work);
};
}
module.exports = wrappy(asyncOnce);