javascript - 从 forEach 回调中修改外部数组变量

标签 javascript arrays foreach scope

我遇到过类似的问题,但没有一个完全适合我的情况。

在下面的代码中,我使用 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/

相关文章:

javascript - (HTML/CSS) 以有效的方式定位文字/图片,以便考虑窗口收缩

javascript - 集合教程中的 ko.observable 变量

javascript - 让 Javascript 在弹出窗口中显示 HTML

javascript - 如何修改 Javascript 中对象克隆数组中的对象值

javascript - 从javascript中的类对象获取字节数组?

r - 在 R 中使用 %dopar% 而不是 %do% 时出错(包 doParallel)

javascript - 如何获取相同类名的每个值?

javascript - 在 ChartJS 中对标签进行换行时,工具提示中出现不需要的逗号

c - 在 C 数组中存储多个项目

java - 我可以在一行 foreach 循环中执行两种方法吗?