I have come across similar questions, but none that quite fits my scenario.
In the code below, I am using the listContainers()
function from the dockerode Javascript library, to list the ids of my Docker containers. The snippet is adapted from one on the dockerode README. The listContainers
call works and the console.log line outputs the ids as expected. The problem is that I cannot push the container IDs into the array declared outside the function call - the result is that the array is still empty after the listContainers
call.
I am not very experienced with Javascript, but I think this problem is due to attempting the push inside the callback function. The problem is that the listContainers is asynchronous, so this means that //CONSOLE LOG #2
actually executes before //CONSOLE LOG #1
.
How can I capture the id values into the ids array outside the function call?
//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());