I'm playing around with promises to try and recursively walk a nested array structure. Here is my test code:
const Promise = require("Bluebird");
let allPaths = [
"foo",
"bar",
[
"baz",
"bazzz",
"bazzzzz",
"xxx",
[
"never"
]
],
"abc",
[
"tst",
[
"111",
"222"
],
"xxx"
],
"zzz"
];
function processThisPath(path) {
return new Promise(function(resolve) {
if (typeof path === "string") {
console.log(`Processing path ${path}`);
return resolve(path);
}
else {
return new Promise(function(resolve) {
console.log("PROCESSING NEW LEVEL");
return Promise.each(
path,
processThisPath
);
});
}
});
}
Promise.each(
allPaths,
function(currentPath) {
return (
processThisPath(currentPath)
.catch(function(err) {
console.log(`Cannot traverse '${currentPath}': ${err.message}`);
})
);
}
);
It doesn't traverse the entire structure and I can't figure out why. The output is:
Processing path foo
Processing path bar
PROCESSING NEW LEVEL
Processing path baz
Processing path bazzz
Processing path bazzzzz
Processing path xxx
PROCESSING NEW LEVEL
Processing path never
Why does it not move on to "abc"
? I'd have thought the initial Promise.each
would move on to the next entry in the array, but it seems to have stopped when it got to the first array. Why?