I have the following recursive function that works beautifully when the output from transformItem is synchronous, but I've been having a very difficult time figuring out how to refactor it when transformItem returns a a promise and still get the same type of desired final object output.
function transformStack(target, stack){
var stackItem = stack.shift();//Copy Value
util.logData(_this.context, "Target:" + JSON.stringify(target) + " Stack:" + JSON.stringify(stack), 9);
switch(stackItem){
case "[]":
for(var x=0; x < target.length; x++){
//Copies values so not by Ref any more
var nextTarget = JSON.parse(JSON.stringify(target[x]));
if(stack.length > 0){
util.logData(_this.context, "Loop[]:" + JSON.stringify(nextTarget), 8);
target[x] = transformStack(nextTarget, JSON.parse(JSON.stringify(stack)));
} else {
util.logData(_this.context, "TransformTarget[]:" + JSON.stringify(nextTarget), 8);
target[x] = transformItem(nextTarget);
}
}
break;
default:
//Copies values so not by Ref any more
var nextTarget = JSON.parse(JSON.stringify(target[stackItem]));
if(stack.length > 0){
util.logData(_this.context, "Loop:" + JSON.stringify(nextTarget), 8);
target[stackItem] = transformStack(nextTarget, JSON.parse(JSON.stringify(stack)));
} else {
util.logData(_this.context, "TransformTarget:" + JSON.stringify(nextTarget), 8);
target[stackItem] = transformItem(nextTarget);
}
}
return target;
}
I created this base JSFiddle which illustrates this a little better on what I'm expecting:
https://jsfiddle.net/fxay76k8/9/
Can anyone help point me in the right direction? I've been looking at the following Stack Overflow post, but haven't been able to apply it properly to my flow: JavaScript : Calling Recursive Functions With Promises
Thank-you for your help!
BTW, I'm using Q for the promises, but I'm pretty confident I can translate any other promise libraries over to what I need if someone can help me with the concepts here.