2016-07-21 2 views
0

Я пытаюсь загрузить иерархию в моей базе данных. У меня есть столбец с parentId в моей таблице, поэтому каждая строка может иметь родителя. Но у меня проблемы с рекурсией и обещаниями.Запрос Herarchy с использованием sequelize/nodejs

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); 
     }); 
    } 
    }); 
} 

Итак, я называю чтения, который вызывает loadChildren рекурсивно пытаться загрузить все объекты (смотря детей сущности) и я получаю неопределенное значение. Есть идеи?

Я также получаю сообщение об ошибке на консоли: обещание было создано в обработчике, но не было возвращено из него.

EDIT:

Придумал, если это решение после того, как Nosyara помощь. спасибо !:

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 then 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); 
      }); 
     }); 
     } 
    }); 
    }); 
} 

ответ

0

Вы messing с асинхронными вызовами и возвращается. Вы можете преобразовать обе функции в async и пройти через структуру результатов, подлежащую обновлению. Пример:

function read(...) { 
    return new Promise(function (accept, reject) { 
    // You code goes here, but instead of return 
    accept(resultFromAsyncFunction); 
    }); 
} 
// ... 
read(...).then(function(resultData) { ... }); 

Here является примером репликации обещаний.

+0

Я изменил код, чтобы посмотреть, как у вас .... но он все еще не работал – fredcrs

+0

получил некоторый прогресс ..... еще косяк нагрузки уровень 3-й – fredcrs

+0

код так далеко: http://pastebin.com/Na5NHkMm – fredcrs

Смежные вопросы