forked from meteorhacks/npm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (77 loc) · 2.27 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
78
79
80
81
82
83
84
85
86
87
88
var Future = Npm.require('fibers/future');
Async = {};
Meteor.require = function(moduleName) {
var module = Npm.require(moduleName);
return module;
};
Async.runSync = Meteor.sync = function(asynFunction) {
var future = new Future();
var sent = false;
var payload;
var wrappedAsyncFunction = Meteor.bindEnvironment(asynFunction, function(err) {
console.error('Error inside the Async.runSync: ' + err.message);
returnFuture(err);
});
setTimeout(function() {
wrappedAsyncFunction(returnFuture);
}, 0);
future.wait();
sent = true;
function returnFuture(error, result) {
if(!sent) {
payload = { result: result, error: error};
future.return();
}
}
return payload;
};
Async.wrap = function(arg1, arg2) {
if(typeof arg1 == 'function') {
var func = arg1;
return wrapFunction(func);
} else if(typeof arg1 == 'object' && typeof arg2 == 'string') {
var obj = arg1;
var funcName = arg2;
return wrapObject(obj, [funcName])[funcName];
} else if(typeof arg1 == 'object' && arg2 instanceof Array) {
var obj = arg1;
var funcNameList = arg2;
return wrapObject(obj, funcNameList);
} else {
throw new Error('unsupported argument list');
}
function wrapObject(obj, funcNameList) {
var returnObj = {};
funcNameList.forEach(function(funcName) {
if(obj[funcName]) {
var func = obj[funcName].bind(obj);
returnObj[funcName] = wrapFunction(func);
} else {
throw new Error('instance method not exists: ' + funcName);
}
});
return returnObj;
}
function wrapFunction(func) {
return function() {
var args = arguments;
response = Meteor.sync(function(done) {
Array.prototype.push.call(args, done);
func.apply(null, args);
});
if(response.error) {
//we need to wrap a new error here something throw error object comes with response does not
//print the correct error to the console, if there is not try catch block
var error = new Error(response.error.message);
for(var key in response.error) {
if(error[key] === undefined) {
error[key] = response.error[key];
}
}
throw error;
} else {
return response.result;
}
};
}
};