【问题标题】:In JavaScript, how to implement a recursive `ancestors()` function when `parent()` returns a Promise在 JavaScript 中,当 `parent()` 返回一个 Promise 时,如何实现递归 `ancestors()` 函数
【发布时间】: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


【解决方案1】:

如果方法.parent()返回一个promise,它的实现值将是父级,当没有更多父级时它返回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!
猜你喜欢
  • 2017-06-09
  • 1970-01-01
  • 2022-01-02
  • 2022-01-26
  • 2013-10-10
  • 2021-01-31
  • 2022-11-29
  • 2020-06-25
  • 2022-08-03
相关资源
最近更新 更多