【问题标题】:Async / Await Reactjs异步/等待 Reactjs
【发布时间】:2019-08-08 22:06:54
【问题描述】:

我正在尝试在我的 react/electron 项目中使用 async/await,但它不是 workink。 我想要的是获取 docker 容器状态列表。 但是 console.log(list) 返回 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++;
      });
    });
  }

有人可以帮帮我吗? :)

【问题讨论】:

标签: node.js reactjs electron


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-03-04
    • 1970-01-01
    • 2023-03-12
    • 2016-07-07
    • 2016-03-25
    • 2017-10-09
    • 2021-10-22
    相关资源
    最近更新 更多