-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (47 loc) · 1.12 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
const nodeCo = require('./build/Release/node-coroutine');
const Co = new nodeCo.Coroutine();
function realCallback(fn){
return function(){
var arg = [...arguments];
var gen, ret;
gen = fn.apply(global,arg);
while(1){
ret = gen.next();
if(ret.done){
Co.done(ret.value.yield);
Co.swap();
return;
}else{
if(!ret.value || !ret.value.yield){
Co.swap();
}else{
Co.swap(ret.value.yield)
}
}
}
}
}
function create(fn){
if(fn.constructor.name != "GeneratorFunction"){
fn = function*(params){
fn.apply(global,params);
yield;
}
}
fn = realCallback(fn);
var CoYield = Co.create(fn);
retFn = function(){
var arg = [...arguments];
CoYield.arguments = arg;
Co.swap(CoYield);
}
retFn.yield = CoYield;
return retFn;
}
function destroy(fn){
Co.destroy(fn.yield);
}
module.exports = {
create: create,
destroy: destroy
}