Search code examples
angularpromiseangular2-servicesangular-promisesession-storage

How to return a value within a promise in angular 2


I want to check sessionStorage (sessionStorage['new']) for a value and if it exists, I want to return it and disregard the rest of the function, but I get an error that then is not defined. I'm not sure what I'm doing wrong.

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);
    });
}

This is the error:

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

Solution

  • The error doesn't state that then is not defined.

    You are setting treeLoadedPromise to whatever is returned from sessionStorage["new"]. This value isn't going to be a promise. If the item is present, this will return a string, otherwise it will be undefined.

    I'm guessing you want something like this:

    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);
        }
    }