首页 > 解决方案 > Javascript Promise - 带返回值的递归 - “记住层次结构”

问题描述

我正在尝试为 Omnifocus 编写一个“同步”(部分)插件,从YouTrack重新创建分层任务。OF 提供了通过称为Fetch API的东西调用经过身份验证的 RESTful API 的能力,该API返回一个承诺。

设置:例如,这是 youtrack 中的任务层次结构:

Task 1
|____Task 1A
      |____Task 1 A.A
           |___ Task x

目标:我的目标是,从issueId双向遍历树开始,同时在处理每个级别的每个节点时都知道你的父母。对于上述设置,我们假设起始问题是Task 1 A.A. 对于遍历孩子,我相信这个过程很简单。当前问题已添加到层次结构中,并且使用提供给它们的层次结构信息对子级进行递归:

function issueProcessor(issueID, hierarchy = [], level = 0) {
if (level > 4) {
    throw new Error("Too deep");
}
// This returns a promise which would resolve to the JSON object containing API response
issueGet = getIssueFetchobject(issueID);
issueGet.then(function (apiResponse) {
    if (isItMe(apiResponse)) {
        parent = apiResponse.parent.idReadable;
        if (parentAPIResponse.parent.issues.length > 0 && hierarchy.length < 1) {
          /*
          This doesn't work.
          */
            hierarchy = parentProcessor(parent);
        }
        createOFAction(apiResponse.summary, apiResponse.project.name, hierarchy, level);
        // Add yourself to hierarchy
        hierarchy.add(apiResponse.summary);
        var child;
        for (child of apiResponse.subtasks) {
            issueProcessor(child.idReadable, hierarchy,level + 1);
        }
    }
});
}

Processing Parent 是我大脑崩溃的地方,我无法让它工作。

function parentProcessor(issueID, hierarchy = [], level = 0) {
if (level < -4) {
    throw new Error("Too deep");
}
issueGet = getIssueFetchobject(issueID);
return issueGet.then(function (parentAPIResponse) {
    if (parentAPIResponse.parent.issues.length > 0) {
        return parentProcessor(parentAPIResponse.parent.issues[0].idReadable, hierarchy, level - 1)
    }
    console.log(`${level} : Parents are dealt with, now my turn`);
    h = JSON.stringify(hierarchy);
    console.log(`${level}: Hierarchy is ${h}`);
    createOFAction(parentAPIResponse.summary, parentAPIResponse.project.name, hierarchy, level);
    return hierarchy.add(parentAPIResponse.summary);
});

}

这是调用父处理器时的输出Task 1 A.A
parentProcessor(issueID, []).then(function (x) { console.log(x); })

-2 : 父母处理好了,现在轮到我了
-2 : Hierarchy is []
-2 : Creating task Task 1 AA under

即只处理最老的父级(级别 = -2),其余的根本不处理。我期望看到的当然是级别 -1 和 0 处理,最后得到一个像这样的数组:

[任务 1、任务 1A、任务 1 AA]

我在其他地方使用递归的经验告诉我,我实际上不需要单独的parentProcessor函数,因为操作非常相似,但我无法通过引入 promise 和增量向数组添加元素来协调递归。

标签: javascriptrecursionpromiseomnifocus

解决方案


推荐阅读