簡體   English   中英

從forEach回調中修改外部數組變量

[英]Modifying external array variable from within forEach callback

我遇到了類似的問題,但沒有一個完全適合我的情況。

在下面的代碼中,我正在使用dockerode Javascript庫中的listContainers()函數列出我的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);
                }
            });
});

您無需將全局變量ID與回調一起傳遞,

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

//Shows that the array is empty
console.log("IDs: "+ids.toString());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM