From 6abfb9bd70a1df160145eb90b8a44bef071da38d Mon Sep 17 00:00:00 2001 From: Max Nordlund Date: Mon, 8 Dec 2014 00:34:57 +0100 Subject: [PATCH] Add try/catch helper to fix #148 --- runtime.js | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/runtime.js b/runtime.js index d106a3428..d3178f63d 100644 --- a/runtime.js +++ b/runtime.js @@ -25,6 +25,16 @@ return new Generator(innerFn, outerFn, self || null, tryList || []); } runtime.wrap = wrap; + + // Try/catch helper to minemize deoptimizations + var _try = function(block) { + try { + block(); + return undefined; + } catch (err) { + return err; + } + } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; @@ -66,10 +76,12 @@ var callThrow = step.bind(generator["throw"]); function step(arg) { - try { - var info = this(arg); + var self = this, error = _try(function() { + var info = self(arg); var value = info.value; - } catch (error) { + }); + + if (error) { return reject(error); } @@ -101,8 +113,8 @@ while (true) { var delegate = context.delegate; if (delegate) { - try { - var info = delegate.iterator[method](arg); + var info, uncaught = _try(function() { + info = delegate.iterator[method](arg); // Delegate generator ran and handled its own exceptions so // regardless of what the method was, we continue as if it is @@ -110,7 +122,9 @@ method = "next"; arg = undefined; - } catch (uncaught) { + }) + + if (uncaught) { context.delegate = null; // Like returning generator.throw(uncaught), but without the @@ -166,9 +180,11 @@ state = GenStateExecuting; - try { - var value = innerFn.call(self, context); + var value, thrown = _try(function() { + value = innerFn.call(self, context); + }) + if (!thrown) { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done @@ -190,7 +206,7 @@ return info; } - } catch (thrown) { + } else { state = GenStateCompleted; if (method === "next") {