-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
56 lines (49 loc) · 1.3 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
var co = require("co");
module.exports = function(fn) {
return isGeneratorFunction(fn) ? gWrapper(fn) : aWrapper(fn);
}
/*
* generator wrapper
*/
function gWrapper(fn) {
if (fn.length == 4) return function(err, req, res, next) {
return co(fn.call(this, err, req, res, next)).catch(next);
}
return function() {
return co(fn.apply(this, arguments)).catch(arguments[arguments.length - 1]);
}
}
/*
* async wrapper
*/
function aWrapper(fn) {
if (fn.length == 4) return function(err, req, res, next) {
return fn.call(this, err, req, res, next).catch(next);
}
return function() {
return fn.apply(this, arguments).catch(arguments[arguments.length - 1]);
}
}
/**
* Check if `obj` is a generator.
*
* @param {Mixed} obj
* @return {Boolean}
* @api private
*/
function isGenerator(obj) {
return '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) {
var constructor = obj.constructor;
if (!constructor) return false;
if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
return isGenerator(constructor.prototype);
}