[removed] sync to async converter libs

2019-04-01 21:02发布

1) What is better streamlinejs: https://github.com/Sage/streamlinejs or narrative: http://www.neilmix.com/narrativejs/ ? any others libs?

2) How does any of those libraries even work? (I read the docs, I am looking for a simplify explanation of what's going on behind the scene..)

1条回答
劫难
2楼-- · 2019-04-01 21:37

As far as question #2....in general these things:

  1. parse javascript into some abstract syntax tree (AST)
  2. transform the AST
  3. stringify the transformed tree back into javascript

I wrote a partial converter as a learning experience a while back. I used uglify.js to parse into an AST and then the tree walker that lib provides to do the transformations. The transformations were general purpose and produced code that looked like a state machine -- where each step started with a sequence of 0 or more sync actions and ended with an async action. E.g. this simple script:

var fs = require('fs');
console.log(fs.readFile('input.js', _).toString('utf-8'));

would get converted to this:

var fs, $v_0;

function s_0() {
    fs = require("fs");
    fs.readFile("input.js", function(err, res) {
        if (err) s_err(err); else {
            $v_0 = res;
            s_1();
        }
    })
}

function s_1() {
    console.log($v_0.toString("utf-8"));
}

s_0()

I imagine that streamline and the like do something very similar. Certain structures (loops, try/catch) need special handing but the general approach is the same -- convert into a state machine.

The issues with this approach that I found were:

1) it's not a local problem - i.e. any async behavior that needs to be handled infects everything all the way up the call stack.

2) you need function metadata so you either have to make assumptions or require people to annotate their functions in some manner.

查看更多
登录 后发表回答