我遇到过类似的问题,但没有一个完全适合我的情况。
在下面的代码中,我使用 dockerode 中的 listContainers()
函数。 Javascript 库,用于列出我的 Docker 容器的 ID。该片段改编自 dockerode README 上的片段。 listContainers
调用有效,console.log 行按预期输出 id。问题是我无法将容器 ID 插入在函数调用外部声明的数组中 - 结果是在 listContainers
调用之后数组仍然为空。
我对 Javascript 的经验不是很丰富,但我认为这个问题是由于尝试在回调函数内进行推送造成的。问题在于 listContainers 是异步的,因此这意味着 //CONSOLE LOG #2
实际上在 //CONSOLE LOG #1
之前执行。
如何在函数调用之外将 id 值捕获到 ids 数组中?
//Here is where I want to store my container ids.
var ids = [];
//Here is the dockerode call
dockerCli.listContainers(function(err, containers) {
containers.forEach(function(containerInfo) {
//log shows the correct id
console.log(containerInfo.Id);
//Here I try to save the container id to my array
ids.push(containerInfo.Id);
});
//CONSOLE LOG #1 Here I can see that the array has the correct values
console.log("IDs: "+ids.toString());
});
//CONSOLE LOG #2 Shows that the array is empty
console.log("IDs: "+ids.toString());
最佳答案
在其他评论者的帮助下,我意识到 listContainers
调用是异步的,并且根本没有办法从中返回值。
那么如何初始化和使用我的 ids
数组呢?我创建了自己的函数来包装 dockerode listContainers 调用。然后,该函数使用自己的回调来处理 ids 数组。这允许我在自己的回调中访问初始化的 ids 数组,将处理 ids 数组的功能与获取容器列表的功能分开。
ids = [];
//Define my function that takes a callback function
//and just fetch the container ids
function getContainerJsonFromDocker(callback) {
dockerCli.listContainers(function(err, containers) {
containers.forEach(function(containerInfo) {
console.log(containerInfo.Id);
ids.push(containerInfo.Id);
});
return callback(ids);
});
}
//Now call my function, and pass it an anonymous callback
//The callback does the processing of the ids array
getContainerJsonFromDocker(function(ids) {
//This shows the array is initialised :)
console.log("IDs: " + ids.toString());
//Write my array to .json file
var outputFilename = 'data.json';
fs.writeFile(outputFilename, JSON.stringify(ids, null, 4),
function(err) {
if (err) {
console.log(err);
} else {
console.log("JSON saved to " + outputFilename);
}
});
});
关于javascript - 从 forEach 回调中修改外部数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33809079/