-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
77 lines (68 loc) · 1.71 KB
/
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
var defaultTimeout = 1000;
function until(_latch, _message, _timeout) {
var start = new Date().getTime();
var latchFunction = null;
var message = null;
var timeout = null;
if (arguments.length > 3) {
throw new Error('until only takes up to 3 args');
}
for (var i = 0; i < arguments.length; i++) {
switch (typeof arguments[i]) {
case 'function':
latchFunction = arguments[i];
break;
case 'string':
message = arguments[i];
break;
case 'number':
timeout = arguments[i];
break;
}
}
message = message || 'something happens';
timeout = timeout || defaultTimeout;
var error;
var setError = function(err) {
if (typeof err === 'string') {
error = new Error(err);
} else {
error = err;
}
return false;
};
return new Promise(function(resolve, reject) {
var checker = function() {
Promise.resolve(latchFunction(setError))
.catch(err => {
setError(err);
return false;
})
.then(result => {
if (result) {
return resolve(result);
} else {
var now = new Date().getTime();
var delta = now - start;
if (delta > timeout) {
if (!error) {
error = new Error('timed out waiting until ' + message);
}
error.message = 'async(' + timeout + 'ms): ' + error.message;
return reject(error);
} else {
return setTimeout(checker);
}
}
})
};
checker();
});
}
until.setDefaultTimeout = function(ms) {
if (!ms) {
ms = 1000;
}
defaultTimeout = ms;
};
module.exports = until;