mirror of
https://github.com/embarklabs/embark.git
synced 2025-02-03 01:13:55 +00:00
Better support for await
This commit is contained in:
parent
a43627de5b
commit
3a210f602b
@ -1,4 +1,5 @@
|
|||||||
const RunCode = require('./runCode.js');
|
const RunCode = require('./runCode.js');
|
||||||
|
const Utils = require('../../../utils/utils');
|
||||||
|
|
||||||
class CodeRunner {
|
class CodeRunner {
|
||||||
constructor(options) {
|
constructor(options) {
|
||||||
@ -59,19 +60,23 @@ class CodeRunner {
|
|||||||
this.runCode.registerVar(varName, code);
|
this.runCode.registerVar(varName, code);
|
||||||
}
|
}
|
||||||
|
|
||||||
evalCode(code, cb, forConsoleOnly = false) {
|
async evalCode(code, cb, forConsoleOnly = false) {
|
||||||
cb = cb || function() {};
|
cb = cb || function() {};
|
||||||
const awaitIdx = code.indexOf('await');
|
const awaitIdx = code.indexOf('await');
|
||||||
|
let awaiting = false;
|
||||||
|
|
||||||
if (awaitIdx > -1) {
|
if (awaitIdx > -1) {
|
||||||
if (awaitIdx < 2) {
|
awaiting = true;
|
||||||
let end = code.length;
|
const instructions = Utils.compact(code.split(';'));
|
||||||
if (code[end - 1] === ';') {
|
const last = instructions.pop();
|
||||||
end--; // Remove the `;` because we add function calls
|
|
||||||
}
|
if (!last.trim().startsWith('return')) {
|
||||||
code = code.substring(5, end); // remove await keyword
|
instructions.push(`return ${last}`);
|
||||||
} else {
|
} else {
|
||||||
code = `(async function() {${code}})();`;
|
instructions.push(last);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
code = `(async function() {${instructions.join(';')}})();`;
|
||||||
}
|
}
|
||||||
let result = this.runCode.doEval(code);
|
let result = this.runCode.doEval(code);
|
||||||
|
|
||||||
@ -80,11 +85,16 @@ class CodeRunner {
|
|||||||
this.ipc.broadcast("runcode:newCommand", {code});
|
this.ipc.broadcast("runcode:newCommand", {code});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result instanceof Promise && !result.on) {
|
if (!awaiting) {
|
||||||
return result.then((value) => { cb(null, value); }).catch(cb);
|
return cb(null, result);
|
||||||
}
|
}
|
||||||
|
|
||||||
cb(null, result);
|
try {
|
||||||
|
const value = await result;
|
||||||
|
cb(null, value);
|
||||||
|
} catch (error) {
|
||||||
|
cb(error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user