1

How can I call functions one-by-one after completing? I have code like that, which must be executed continuously.

For example, I have:

var Connection = require('ssh2');

var c = new Connection();
c.on('connect', function() {
  console.log('Connection :: connect');
});
c.on('ready', function() {
  console.log('Connection :: ready');
  c.exec('uptime', function(err, stream) {
    if (err) throw err;
    stream.on('data', function(data, extended) {
      console.log((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ')
                  + data);
    });
    stream.on('end', function() {
      console.log('Stream :: EOF');
    });
    stream.on('close', function() {
      console.log('Stream :: close');
    });
    stream.on('exit', function(code, signal) {
      console.log('Stream :: exit :: code: ' + code + ', signal: ' + signal);
      c.end();
    });
  });
});
c.on('error', function(err) {
  console.log('Connection :: error :: ' + err);
});
c.on('end', function() {
  console.log('Connection :: end');
});
c.on('close', function(had_error) {
  console.log('Connection :: close');
});
c.connect({
  host: '192.168.100.100',
  port: 22,
  username: 'frylock',
  privateKey: require('fs').readFileSync('/here/is/my/key')
});

In what way can I call several functions one-by-one? When the connection to the ssh2 server is established, and the first request is executed, I have to parse the output of this request and send another request with data from the previous request.

I have functions which can do all this; the only problem is how to make another request after the first one is completed.

hopper
  • 13,060
  • 7
  • 49
  • 53
Barterio
  • 670
  • 1
  • 5
  • 18

2 Answers2

0

You can use nested callbacks. In the 'end' handler of each request, create a new connection and setup its end handler. Nest until needed. Similar to:

c.on('end', function() {
    // after c is done, create newC
    var newC = new Connection();
    newC.on('end', function() {
         // more if needed.
    });
});

Another approach is to use some library for promises, like Q, which clears up the syntax a lot.

You can also take a look at this question: Understanding promises in node.js

Community
  • 1
  • 1
Slavo
  • 15,255
  • 11
  • 47
  • 60
0

From the sounds of it, you might want to look into a control flow node module such as async. Also you shouldn't need to tear down the connection just to execute another command on the same server.

mscdex
  • 104,356
  • 15
  • 192
  • 153