i trying load hierarchy in database. have column parentid in table every row can have parent. having problems using recursion , promises.
function read (options) { return serviceitemattributemodel.findone({ id: options.id, id_organization: options.idorganization }) .then((attribute) => { if (attribute) { return loadchildren(attribute, attribute); } else { return attribute; } }); } function loadchildren (root, attribute) { return serviceitemattributemodel.findall({ where: { id_parent: attribute.id } }) .then((attributes) => { if (!attributes) { return root; } else { attribute.serviceitemattributes = []; attributes.foreach(function (each) { attribute.serviceitemattributes.push(each); return loadchildren(root, each); }); } }); }
so, call read calls loadchildren recursively try load entities (by looking children of entity) , undefined value. ideas?
i getting error on console: promise created in handler not returned it.
edit:
came if solution after nosyara help. thanks!:
function read (options) { return serviceitemattributemodel.findone({ where: { id: options.attributeid, id_organization: options.idorganization } }) .then((attribute) => { if (!attribute) { return new promise(function (resolve, reject) { resolve(attribute); }); } else { return new promise(function (resolve, reject) { attribute.querycount = 1; resolve(attribute); }) .then((attribute) => loadchildren(attribute, attribute)); } }); } function loadchildren (root, attribute) { return new promise(function (resolve, reject) { return serviceitemattributemodel.findall({ where: { id_parent: attribute.id } }) .then((attributes) => { attributes.length = attributes.length || 0; root.querycount = root.querycount - 1 + attributes.length; if (root.querycount === 0) { resolve(root); } else if (root.querycount > 10) { let error = new error('service attribute hierarchy cant have more 10 levels'); error.statuscode = 500; reject(error); } else { attribute.serviceitemattributes = []; attributes.foreach(function (each) { attribute.serviceitemattributes.push(each); return loadchildren(root, each).then(() => { resolve(root); }); }); } }); }); }
you messing async calls , returns. can convert both function async, , pass through result structure updated. example:
function read(...) { return new promise(function (accept, reject) { // code goes here, instead of return accept(resultfromasyncfunction); }); } // ... read(...).then(function(resultdata) { ... });
here example of promise recursion.
Comments
Post a Comment