-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
78 lines (69 loc) · 2.17 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
// Copyright 2014, David M. Lee, II
/**
* Add promise support to a repl.
*
* @param {REPLServer} repl The REPL to enrich with handy promise support
*/
module.exports.promirepl = (repl) => {
const realEval = repl.eval;
function promiseEval(cmd, context, filename, callback) {
realEval.call(repl, cmd, context, filename, (err, res) => {
// Error response
if (err) {
callback(err);
return;
}
// Non-thenable response
if (!res || typeof res.then !== 'function') {
callback(null, res);
return;
}
// Thenable detected; extract value/error from it
let cancel;
let hangTimer;
let done = (doneErr, val) => {
// ensure we call the callback only once
// *really* shouldn't be possible, but just in case
done = () => {};
clearTimeout(hangTimer);
process.stdin.removeListener('keypress', cancel);
callback(doneErr, val);
};
// Start listening for escape characters, to quit waiting on the promise
cancel = (chunk, key) => {
if (key.name === 'escape') {
repl.outputStream.write('break.\n');
done(null, res);
}
};
process.stdin.on('keypress', cancel);
// Start a timer indicating that escape can be used to quit
hangTimer = setTimeout(() => {
repl.outputStream.write('Hit escape to stop waiting on promise\n');
}, 5000);
// resolve with the value/error from the promise
res.then(val => done(null, val), resErr => done(resErr))
.catch((uncaught) => {
// Rethrow uncaught exceptions
// *really* shouldn't be possible, but bugs do happen
process.nextTick(() => {
throw uncaught;
});
});
});
}
repl.eval = promiseEval;
repl.commands.promise = {
help: 'Toggle auto-promise unwrapping',
action() {
if (repl.eval === promiseEval) {
this.outputStream.write('Promise auto-eval disabled\n');
repl.eval = realEval;
} else {
this.outputStream.write('Promise auto-eval enabled\n');
repl.eval = promiseEval;
}
this.displayPrompt();
},
};
};