[英]JavaScript: Recursive function with Promise, resolve returns “undefined”
[英]In JavaScript, how to implement a recursive `ancestors()` function when `parent()` returns a Promise
假设我在thing.js
有以下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
实例的连续父项。
我已经看到Array.prototype.reduce
函数可用于链接 Promises,但我不知道要预先链接的 Promises,因为它需要递归查找父、祖父母、曾祖父母等。
关于如何构建这个函数的任何想法?
如果方法.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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.