【发布时间】:2016-06-23 02:47:57
【问题描述】:
假设我在thing.js 中有以下内容:
var db = require('my-database-module');
module.exports = class Thing() {
constructor(id, parentId, name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
static find(id) {
// NOTE: The following find() function returns a Promise.
return db.collection('things').find(id);
}
parent() {
return this.constructor.find(this.parentId);
}
}
通常会通过以下方式找到事物:
var Thing = require('thing');
Thing.find(123).then(function(thing) {
// Do something with `thing`
});
您会注意到我想要实现父/子层次结构。我想添加一个ancestors 函数,该函数为给定的Thing 实例返回一组祖先Thing 对象:
module.exports = class Thing() {
// ...
ancestors() {
var a = []
// Can't figure this out...
return a;
}
}
因为Thing#parent 函数返回一个Promise,我对ancestors 函数应该如何工作感到困惑。它需要递归查找Thing 实例的连续父级。
I've seenArray.prototype.reduce 函数可用于链接 Promise,但我不知道要预先链接的 Promise,因为它需要递归查找父、祖父母、曾祖父母等。
关于如何构造这个函数的任何想法?
【问题讨论】:
标签: javascript recursion tree promise parent-child