Part of my project involves running custom script (pre-existing game scripts). I've previously implemented that in Java. There created my own parser that compiles it into an object tree that can then be executed (as such it's not interpreted anymore). The whole parser is just over 1000 lines of code which doesn't seem too bad. Now, a few years later, I want to run it in the browser and need a JavaScript solution. Perhaps I could have used the same approach again but I was seeking for a better solution. It was clear that I didn't want to write a bespoke interpreter as would have been more difficult to test, is slower and less portable. The logical solution seem to be (and you may disagree) to compile it to JavaScript.

Some of the main challenges:

  • Select a parser generator
  • Generate non-blocking JavaScript
  • Support labels

Read more: Compiling Custom Script to JavaScript

When using JSDeferred you may want to return something immediately. For example if the result was already cached.

The first attempt might look like this:

function doSomething() {
  var deferred = new Deferred();
  deferred.call("the result");
  return deferred;
}

doSomething().next(function(result) {
  console.log(result);
};

The problem of course is that the next function will not have been assigned yet. Fortunately the solution is fairly simple:

function doSomething() {
  return Deferred.next(function() {
    return "the result";
  });
}