diff --git a/lib/nel.js b/lib/nel.js index 04ce867..2a7ab1e 100755 --- a/lib/nel.js +++ b/lib/nel.js @@ -51,15 +51,41 @@ var doc = require("./mdn.js"); // Documentation for Javascript builtins var log = require("./log.js")("NEL:"); var server = require("./server/index.js"); // Server source code +// acts like 'new Promise(fn)', polyfilling if necessary +function newPromise(fn) { + if (global.Promise && typeof global.Promise === "function") { + // we have promises, use them + return new global.Promise(fn); + } else { + // create a dumb little synchronous thenable as a promise polyfill + // NOTE: this assumes that if you don't have built-in promises that your + // function isn't going to return a Promise or thenable + var fnRet, fnErr; + var chainable = { + then: function(thenFn) { + try { + fn(function resolve(v) { + fnRet = v; + }, function reject(e) { + fnErr = e; + }); + } catch (err) { + fnErr = err; + } + + if (!fnErr) thenFn(fnRet, fnErr); + + return chainable; + }, + catch: function(catchFn) { + if (fnErr) catchFn(fnErr); + } + }; -function isPromise(x) { - if (!global.Promise || typeof global.Promise !== "function") { - return false; + return chainable; } - return x instanceof global.Promise; } - // File paths var paths = { node: process.argv[0], @@ -816,27 +842,23 @@ Session.prototype._runNow = function(task) { }).bind(this); if (this.transpile && task.action === "run") { - try { - // Adapted from https://github.com/n-riesco/nel/issues/1 by kebot - var transpiledCode = this.transpile(task.code); - log("SESSION: RUN: TRANSPILE:\n" + transpiledCode + "\n"); - if (isPromise(transpiledCode)) { - transpiledCode.then(function(value) { - task.code = value; - sendTask(); - }).catch(sendError); - return; - } else { + // run asynchronous transpiling using a polyfill if necessary + // for synchronous code this acts like Promise.resolve() + newPromise(function(resolve, reject) { + resolve(this.transpile(task.code)); + }.bind(this)) + .then(function(transpiledCode) { + log("SESSION: RUN: TRANSPILE:\n" + transpiledCode + "\n"); task.code = transpiledCode; - } - } catch (error) { - sendError(error); - return; - } + sendTask(); + }) + .catch(function(err) { + sendError(err); + }); + } else { + // no transpiling, just run task + sendTask(); } - - sendTask(); - return; }; /** diff --git a/package.json b/package.json index 743aa4e..9545a33 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nel", - "version": "1.2.0", + "version": "1.2.1", "description": "Node.js Evaluation Loop (NEL): module to run a Node.js REPL session", "keywords": [ "javascript",