recursion - Why my recursive Javascript function with Promises fails -
i have json object need clean of properties starting $. given structure below should rid of $aaa, $bbb, $ccc , $eee:
{ $aaa: "$aaa", bbb: "bbb", $ccc: { $ccc2: "$ccc2", ccc2a: "ccc2a" }, ddd: { $ddd: "$ddd2", ddd2a: "ddd2a" }, $eee: "$eee", fff: "fff" } i wanted make run asynchronously , use promises. i'm having trouble getting work. fails clean $eee , not sure going wrong. below full code , plunker here:
function clean$(obj1) { var obj = obj1; return new promise(function(res, rej) { settimeout(function() { (var in obj) { if (obj.hasownproperty(i)) { if (i.match(/^\$/)) { console.log("delete " + i); delete obj[i]; } else if (typeof obj[i] === "object") return clean$(obj[i]); } } res(); }, 1000); }) } sample = { $aaa: "$aaa", bbb: "bbb", $ccc: { $ccc2: "$ccc2", ccc2a: "ccc2a" }, ddd: { $ddd: "$ddd2", ddd2a: "ddd2a" }, $eee: "$eee", fff: "fff" } clean$(sample).then(function(res) { console.log("why never gets here???"); })
as @knolleary has said, internal timeout function returning when call $clean, rather continuing.
at point, outer closure has returned promise. promise waiting call res, call never happens.
and initial call waiting promise resolve can write log message "why never gets here???".
you must make sure resolve method called in circumstance. also, has wait internal call $clean resolve.
here working solution:
function clean$(obj1) { var obj = obj1; return new promise(function(res, rej) { settimeout(function() { var promisestowaitfor = []; (var in obj) { if (obj.hasownproperty(i)) { if (i.match(/^\$/)) { console.log("delete " + i); delete obj[i]; } else if (typeof obj[i] === "object") { promisestowaitfor.push(clean$(obj[i])); } } }; promise.all(promisestowaitfor).then(res); }, 1000); }) }
Comments
Post a Comment