-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcallbacks.js
35 lines (32 loc) · 967 Bytes
/
callbacks.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
const fs = require('fs');
const science = require('../console');
// Define this wrapper once and export it
callbackScience = (name, block, next) => {
science(name, (experiment) => {
experiment.async(true);
// Overwrite #try()
experiment.try = (name, block) => {
if (!block) {
block = name;
name = "candidate";
}
experiment.constructor.prototype.try.call(experiment, name, () => {
// Wrap callback as promise
return new Promise((resolve, reject) => {
block((error, result) => {
error ? reject(error) : resolve(result);
});
});
});
};
block(experiment);
}).then(
(res) => next(null, res)
, (err) => next(err, null)
);
};
// Example usage
callbackScience('read file', (experiment) => {
experiment.use((next) => fs.readFile("package.json", next));
experiment.try((next) => next(null, fs.readFileSync("package.json")));
}, console.log);