0

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?

Volando
  • 64
  • 7
  • 1
    You *still* need to `await` it. You cannot convert a promise to a synchronous value, even with an async IIFE like `export const TestState = (async () => { return await test })()` [Async function returning promise, instead of value](https://stackoverflow.com/q/51338277) – VLAZ Dec 13 '21 at 12:09
  • So how could I assign it to my `const initialState` in that case? – Volando Dec 13 '21 at 12:12
  • 1
    "*a promise even though the service is async*" doesn't make sense. It's a promise precisely **because** the service is asynchronous. – Bergi Dec 13 '21 at 13:14

1 Answers1

0

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

Nizar Zizoune
  • 473
  • 6
  • 17