-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
61 lines (52 loc) · 1.23 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
var co = require('co')
var ms = require('ms')
module.exports = function (fn, timeout, logger) {
return function (done) {
if (isGenerator(fn) || isGeneratorFunction(fn))
fn = co(fn)
if (typeof timeout === 'string')
timeout = ms(timeout)
if (typeof timeout !== 'number')
throw new TypeError('invalid timeout')
var ctx = this
var called = false
var id = setTimeout(function () {
var err = new Error('timeout of ' + timeout + 'ms exceeded')
err.status = 408
err.exposed = true
err.timeout = timeout
called = true
done(err)
}, timeout)
fn.call(this, function () {
if (called)
return logger && logger.apply(ctx, arguments)
clearTimeout(id)
done.apply(ctx, arguments)
})
}
}
/**
* Check if `obj` is a generator.
*
* @param {Mixed} obj
* @return {Boolean}
* @api private
*/
function isGenerator(obj) {
return obj
&& 'function' === typeof obj.next
&& 'function' === typeof obj.throw
}
/**
* Check if `obj` is a generator function.
*
* @param {Mixed} obj
* @return {Boolean}
* @api private
*/
function isGeneratorFunction(obj) {
return obj
&& obj.constructor
&& 'GeneratorFunction' === obj.constructor.name
}