0

I'm trying to use async/await in my react/electron project but it's not workink. What i want is to get the list of docker containers status. But console.log(list) returns undefined.

async componentDidMount() {
    let list = await this.getDockerList();
    console.log(list);
  }

  async getDockerList() {
    let files = fs.readdirSync('/home/Docker');
    let dockerList = [];
    let index = 0;
    await files.forEach(async function (value, i) {
      await exec('docker ps -a -q --filter=name=' + value + '_web_1 --filter=status=running', (err, stdout) => {
        if (stdout !== '') {
          dockerList[i] = { name: value, status: 1 };
        } else {
          dockerList[i] = { name: value, status: 0 };
        }
        if ((index + 1) === files.length) {
          console.log('returned');
          return dockerList;
        }
        index++;
      });
    });
  }

Can someone help me please ? :)

  • 2
    Two problems. One is https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop . Another is https://stackoverflow.com/questions/30763496/how-to-promisify-nodes-child-process-exec-and-child-process-execfile-functions . – Estus Flask Mar 18 '19 at 14:02
  • I would strongly recommend using dockerode (https://www.npmjs.com/package/dockerode) instead of directly running commands, there are a lot of security precautions to think about when using exec. There is even an example of listing containers https://github.com/apocas/dockerode/blob/master/examples/listContainers.js – Botto Mar 18 '19 at 14:17
  • You can prefer this it could be help full to you [https://stackoverflow.com/questions/44090197/] – MohammadTausif Shaikh Mar 18 '19 at 14:38

1 Answers1

0

Your function getDockerList() is not inside your this scope, You can either convert your function to a fat arrow function getDockerList = async () => {} like this or you can bind this to your function this.getDockerList = this.getDockerList.bind(this) inside your constructor.

Rishabh Rawat
  • 849
  • 6
  • 11