node.js - 异步/等待 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++;
});
});
}
有人能帮助我吗 ?:)
解决方案
您的函数getDockerList()
不在您的this
范围内,您可以将函数转换为getDockerList = async () => {}
像这样的胖箭头函数,也可以将 this 绑定到this.getDockerList = this.getDockerList.bind(this)
构造函数中的函数。
推荐阅读
- javascript - 无法将 CryptoJS HMAC 生成的签名与 Java HMAC 签名匹配
- git - 本地副本上的 git 更改丢失
- java - 如何在 Android Java 的运行时将 snapchat auth 客户端 ID 更改为另一个?
- javascript - 使用事件引用删除事件侦听器
- sql - SQL - 如果客户购买了产品 A,则返回“True”,否则返回“False”
- python - Python - 基于分布的随机值生成
- javascript - 如何将我的所有资产(Html、JS、CSS、node.JS)放入反应中?
- javascript - 关于传递 JavaScript 方法的问题
- javascript - 猫鼬填充一对多属性
- flutter - ScrollView 内的垂直 ListView 颤动