This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
/
mocha_task.js
126 lines (111 loc) · 2.71 KB
/
mocha_task.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/**
* MochaTask manager.
* Used to provide generator yields for mocha test.
*/
var MochaTask = (function() {
var current, done, errorHandler;
function clearState() {
done = null;
current = null;
errorHandler = null;
}
return {
/**
* Starts a task this will
* effect the global state of MochaTask.
*
*
* @param {Function} generator generator function.
* @param {Function} success success callback.
* @param {Function} error error callback receives an Error instance.
*/
start: function(generator, success, error) {
current = generator;
if (!current.next) {
current = generator.call(this);
}
done = success;
errorHandler = error;
if (current && current.next) {
current.next();
}
return this;
},
/**
* Sends next value to the generator.
* Function may be passed to functions
* that normally require a callback.
*
* yield setTimeout(100, MochaTask.next)
*
* If next is called with a value it will be passed
* to the generators send method so you can use it to
* create this kind of code.
*
* var responseText = yield magicXhrMethod('GET', url, Mocha.next);
*
* @param {Object} value object to pass to generator.
*/
next: function(value) {
//assign references so we
//can clear state without messing
//up execution order later.
var complete = done,
generator = current,
handler = errorHandler;
try {
generator.send(value);
} catch (e) {
if (e instanceof StopIteration) {
clearState();
if (complete) {
complete();
}
} else {
clearState();
if (handler) {
handler(e);
}
}
}
},
nextNodeStyle: function(error, value) {
//assign references so we
//can clear state without messing
//up execution order later.
var complete = done,
generator = current,
handler = errorHandler;
if (error) {
try {
generator.throw(error);
} catch (e) {
if (!(e instanceof StopIteration)) {
handler(e);
} else {
clearState();
if (complete) {
complete();
}
}
}
return;
}
try {
generator.send(value);
} catch (e) {
if (e instanceof StopIteration) {
clearState();
if (complete) {
complete();
}
} else {
clearState();
if (handler) {
handler(e);
}
}
}
}
};
}());