P
P
pgs2018-11-11 12:30:41
JavaScript
pgs, 2018-11-11 12:30:41

Asynchronous functions in a for in/forEach loop, which is correct?

Hello!
I want to loop through the ip list through node.js, connect to each via ssh and remove the information.
I'm using the npm "simple-ssh" package:

const SSH = require('simple-ssh');
const hosts = ['192.168.10.1', '192.168.20.1',];
hosts.forEach(function (ip) {
    //console.log(ip);
    const ssh = new SSH({
        host: ip,
        port: '22',
        user: 'root',
        pass: 'password'
    });

    ssh
        .exec('cat /proc/uptime', {
            out: function(stdout) {
                console.log(hosts);
                console.log(stdout);
            }
        })
        .start();

});

As a result, I get the result of connecting only to the first server:
[ '192.168.10.1', '192.168.20.1' ]
152026.84 148271.15
I understand (maybe wrong) that this is due to the asynchrony of the simple-ssh package, and I need to work with it differently in the cycle , tell me the direction.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2018-11-11
@pgs

Here is a post on the topic (in English)
Try something like this (did not check)

const SSH = require('simple-ssh');
const hosts = ['192.168.10.1', '192.168.20.1',];
async function processIPs(ipArr) {
  for (ip of hosts) {
    //console.log(ip);
    const ssh = new SSH({
        host: ip,
        port: '22',
        user: 'root',
        pass: 'password'
    });

    const pr = new Promise((res, rej) => {
      ssh
      .exec('cat /proc/uptime', {
        out: function(stdout) {
          res(stdout);
        }
      })
      .start();
    });
    
    const result = await pr;
    console.log("ip: %s, result: %s", ip, result);
  }
});

processIPs (hosts);
console.log("Done");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question