Search code examples
javascriptcallbackpromisees6-promise

Unable to get object from promise


I have the following code:

const a = {
    Top: {
        fun: () => {
            return {
                sub: {
                    variable: getResponse().then((response) => response)
                }
            };
        }
    }
};

getResponse() returns a Promise.resolve().

I then try to get the value of variable in another file by doing the following:

let test = importedFile.a.Top.fun().sub.variable.then((resp) => resp);

But when I print out the value of test, instead of getting the value of variable, I get

Promise { <pending>, domain: Domain { domain: null, _events: { error: [Function: handleException] }, _eventsCount: 1, _maxListeners: undefined, members: [] } }

I am sure that in the actual const, variable is getting set to the correct value. I'm just unsure of how to access this separately.

My question is unique as the solution to the other question does not solve this problem.


Solution

  • Once a value is encapsulated in a Promise, it is not possible to get it back out. This is by design. You are forced to write code that uses the encapsulated value in the context of a .then block. This prevents you from using the value before the asynchronous code has resolved it's value.

    let test = importedFile.a.Top.fun().sub.variable.then((resp) => resp);
    expect(test).to.equal(resp); 
    

    This does not work because test is a Promise<typeof resp>, not typeof resp

    You would need to do something like this

    importedFile.a.Top.fun().sub.variable.then((resp) => resp)
      .then(value => {
        expect(value).to.equal(resp);
      });