假设我在 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 seen Array.prototype.reduce
函数可用于链接 Promise,但我不知道要预先链接的 Promises,因为它需要递归地查找父级、祖父级、曾祖父级等。
关于如何构建此函数的任何想法?
最佳答案
如果方法 .parent()
返回一个 promise who's fulfilled value who's fulfilled value would be the parent and it return null
when there is no more parents, then you can write something像这样:
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
});
关于javascript - 在JavaScript中,当 `ancestors()`返回一个Promise时,如何实现一个递归的 `parent()`函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35879543/