0

I am still new to javascript. My problem: I check a folder on a server via ssh. If the folder is empty then I want to return a value (true / 1 / ...). But I just can not get back a value from my function. It always comes back "undefined" ...

What am I doing wrong? I already read something about promise / callback, but even these approaches did not work ... Thank you in advance =)

async function CheckIfDirectoryIsNotEmpty() {

  let value;
  let Client = require('ssh2-sftp-client');
  let sftp = new Client();

  sftp.connect({
    host: 'xxxxx',
    port: 'xx',
    username: 'xxxxxxxx',
    password: 'xxxxxxxx'

    }).then(() => {
      return sftp.list('/opt/cm-shared-data/example/')
    }).then((data) => {
      if(data.length == 0){
        value = 0;
      }
      else { value = 1;}
      sftp.end();
      return value;
    });
}

Call the method:

    async function start() { 


    var a = CheckIfDirectoryIsNotEmpty();

   console.log(a); // "undefined"

}

gegner1111
  • 25
  • 7
  • `CheckIfDirectoryIsNotEmpty` doesn't return anything, so, because you've madeit `async` it will return a promise that will always resolve to `undefined` - what you should do is a) remove the `async` because you never `await` and b) `return sftp.connect ....` - then c) `var a = await CheckIfDirectoryIsNotEmpty();` – Bravo Oct 30 '18 at 07:48
  • `console.log(a); // "undefined"` - I doubt it - probable comes back with a Promise – Bravo Oct 30 '18 at 07:50
  • @Bravo Perfect!! It works!!! thx!!! – gegner1111 Oct 30 '18 at 07:56
  • but do you understand where you went wrong? I hope so :p – Bravo Oct 30 '18 at 07:58
  • Yes! = D Now I understand what I did wrong all the time xD – gegner1111 Oct 30 '18 at 08:06

0 Answers0