Search code examples
javascriptreactjsgraphqlapollo

Returned value is a promise even though the service is async


I have a service.ts that is adding additional data to the one that were previously fetched from Apollo GraphQL. But the data doesn't matter. What matter is - how to grab the returned value?

class TestService implements TestServiceInterface {
  public async fetch(): Promise<any> {
    const result = await apolloClient.query({
      query: gql`
        query Query {
          Test{
           test
           }
            }
          }
        }
      `,
    })


    return {
      graphTitle: "Test",
      graph: "LINE",
      
    };
  }
}

export interface TestServiceInterface {
  fetch(): Promise<any>;
}

How to grab the returned value from TestService in another .ts file?

const test = TestService.fetch()

export const TestState = (async () => {
  return await test
})()

and then:

const initialState = {state: [TestState]}

gives me almost what I need, but now in the component I receive (and still an error):

Promise {   "_U": 0,   "_V": 1,   "_W": Object {  **I have correct values here** }

How to grab the values from inside of the object?


Solution

  • as VLAZ pointed out

    You cannot convert a promise to a synchronous value

    In your code to get the value inside test you should do the following

    const test = await TestService.fetch()
    

    Also refer to the link provided by VLAZ

    Async function returning promise, instead of value