在JavaScript中,当“parent()”返回一个承诺时,如何实现递归的“祖先()”函数
假设我在在JavaScript中,当“parent()”返回一个承诺时,如何实现递归的“祖先()”函数,javascript,recursion,tree,promise,parent-child,Javascript,Recursion,Tree,Promise,Parent Child,假设我在thing.js中有以下内容: var db=require('my-database-module'); module.exports=类对象(){ 构造函数(id、父id、名称){ this.id=id; this.parentId=parentId; this.name=名称; } 静态查找(id){ //注意:下面的find()函数返回一个承诺。 返回db.collection('things').find(id); } 父项(){ 返回this.constructor.find
thing.js中有以下内容:
var db=require('my-database-module');
module.exports=类对象(){
构造函数(id、父id、名称){
this.id=id;
this.parentId=parentId;
this.name=名称;
}
静态查找(id){
//注意:下面的find()函数返回一个承诺。
返回db.collection('things').find(id);
}
父项(){
返回this.constructor.find(this.parentId);
}
}
通常情况下,可通过以下方式完成查找工作:
var Thing=require('Thing');
Thing.find(123).then(函数(Thing){
//用……做某事`
});
您会注意到我想要实现一个父/子层次结构。我想添加一个祖先
函数,该函数为事物
的给定实例返回祖先
对象数组:
module.exports=class Thing(){
// ...
祖先(){
变量a=[]
//我想不出来。。。
返回a;
}
}
由于Thing#parent
函数返回一个承诺,我对祖先
函数应该如何工作感到困惑。它需要递归地查找对象
实例的连续父对象
Array.prototype.reduce
函数可用于链接承诺,但我不知道如何提前链接承诺,因为它需要递归查找父、祖、曾祖等
关于如何构造此函数有什么想法吗?如果方法
.parent()
返回一个承诺值,该值将是父函数,并且在没有更多父函数时返回null
,那么您可以这样写:
ancestors() {
var parents = [];
function getNext(obj) {
return obj.parent().then(function(parent) {
if (!parent) {
// if no more parents, then we must be done with the chain
// so return the whole parent chain
return parents;
} else {
// still got another parent, add to the array and keep going
parents.push(parent);
// returning another promise here chains it to the previous one
return getNext(parent);
}
});
}
return getNext(this);
}
// usage
obj.ancestors().then(function(parents) {
// access to the whole parents array here
});
看一眼,你就会得到。真漂亮。谢谢,@jfriend00!