首页 > 解决方案 > 异步/等待 Reactjs

问题描述

我正在尝试在我的 react/electron 项目中使用 async/await,但它不是 workink。我想要的是获取 docker 容器状态列表。但是 console.log(list) 返回未定义。

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++;
      });
    });
  }

有人能帮助我吗 ?:)

标签: node.jsreactjselectron

解决方案


您的函数getDockerList()不在您的this范围内,您可以将函数转换为getDockerList = async () => {}像这样的胖箭头函数,也可以将 this 绑定到this.getDockerList = this.getDockerList.bind(this)构造函数中的函数。


推荐阅读