如何 return angular 2 中的承诺中的值

How to return a value within a promise in angular 2

我想检查 sessionStorage (sessionStorage['new']) 的一个值,如果它存在,我想 return 它并忽略函数的其余部分,但我得到一个错误那是没有定义的。我不确定我做错了什么。

public getDispositionTree(memberType: string,
                          market: string,
                          includeFiltered: boolean = false,
                          forcedUUIDS: string[] = [],
                          includeArchived: boolean = false): 
    Promise<DispositionTreeNode[]> {

    let treeLoadedPromise;

    if (this.savedDispositionTrees.has(market)) {
        treeLoadedPromise = Promise.resolve();
    } else {
        // **THIS LINE BELOW IS MY CHANGE**
        treeLoadedPromise = sessionStorage['new']
        // treeLoadedPromise = this.loadDispositionTree(market);
    }
    return treeLoadedPromise.then(() => {
        if (includeFiltered) {
            if (includeArchived) {
                return this.savedDispositionTrees.get(market);
            } else {
                return this.getExcludeArchivedDispositionTree(this.savedDispositionTrees.get(market));
            }

        }
        return this.getRelevantDispositionTree(market, memberType, forcedUUIDS);
    });
}

这是错误:

 core.es5.js?0445:1085 ERROR Error: Uncaught (in promise): TypeError: 
 treeLoadedPromise.then is not a function
 TypeError: treeLoadedPromise.then is not a function

错误并未说明 then 未定义。

您正在将 treeLoadedPromise 设置为从 sessionStorage["new"] 编辑的 return。这个值不会是一个承诺。如果该项目存在,这将是 return 一个字符串,否则它将是 undefined.

我猜你想要这样的东西:

let treeLoadedPromise;

if (this.savedDispositionTrees.has(market)) {
    treeLoadedPromise = Promise.resolve();
} else {

    let sessionStorageValue = sessionStorage['new'];
    if (sessionStorageValue !== undefined)
    {
        treeLoadedPromise = Promise.resolve(sessionStorageValue);
    }
    else
    {
        treeLoadedPromise = this.loadDispositionTree(market);
    }
}