Search code examples
node.jsnpmssh2

async/await inside a for loop to access multiple servers using ssh2 do not work


I have this tool that access multiple servers using the npm library ssh2. I want to loop through all these servers to automate an alteration to a certain file inside all these servers. Here is the code snippet of what I have done so far.

const c = require('./constants');

const Client = ssh2.Client;
const conn1 = new Client();
const conn2 = new Client();
const conn3 = new Client();

const serverTuple = [
    [conn1, c.SERVER_1],
    [conn2, c.SERVER_2],
    [conn3, c.SERVER_3]
]

(async () => {
    try {
         serversTuple.forEach(
             async value => await accessServers(value[0], value[1])
         );
    } catch (err) {
         console.log(err);
    }
})

My problem is this:

When I start my program, it goes straight to SERVER_3 without actually processing SERVER_1 and SERVER_2. Is there a way where it can wait for one server to finish first before executing the next one?


Solution

  • You should use a for loop instead of forEach, as forEach doesn't actually await before calling the next item in the array.

    (async () => {
        try {
            for(let value of serversTuple){
                await accessServers(value[0], value[1])
            }
        } catch (err) {
             console.log(err);
        }
    })