0

I've been wondering what's the best way to do this with a language like node.js. Node is asynchronous, but what if we have to make like, 5 calls before we can continue on with the program? I'm putting together something to start my dzen with node.js and had to get the output size. Here's what I have for that:

var geo = require('child_process').exec("i3-msg -t get_outputs",
  function(error, stdout, stderr) {
    var out = JSON.parse(stdout);
    doStuff(out[0].rect);
});

function doStuff(geom) {
// set up dzen
}

out[0].rect is an object that contains x, y, width, and height.

I need these values later on, and this is the only call I have to make, so I don't have to worry about it. But what if I had to make more calls? What if I needed to do a lot of calls, and still had to use node.js? I don't like the idea of something like

var call1 = do.stuff('thing', function(data){
  call2(data);
});

function call2(d1){
  do.more.stuff('yeah', function(data){
    call3(d1, data);
  });
}

function call3(d1,d2){
...
function finallyDone(d1,d2,d3,d4,d5,d6){
// actually use the data now with 6 params

Is this the right way to do it, or is there a better way? I guess I could do something like:

var d1, d2, d3, d4, d5;
var call1 = do.thing(stuff, function(data){
  setd1(data);
});
function setd1(data){
  d1 = data;
  getd2();
}
...
function setd5(data){
  d5 = data;
  getd6();
}
function getd6(){
  var sh = call.thing(stuff, function(data){
    doProgram(data);
  });
}
function doProgram(d6){
  console.log(d1 + d2 + d3 + d4 + d5 + d6);
}

Would that work? Global variables are generally bad though?

4

1 に答える 1

1

You my friend would want to use a library called Async. https://github.com/caolan/async

It lets you chain async requests together with a variety of options on how to have your application behave :)

https://github.com/caolan/async#control-flow-1 is where you would want to look at the examples :)

于 2012-06-23T03:50:35.510 に答える