N
N
Nekdev2022-01-15 22:10:50
JavaScript
Nekdev, 2022-01-15 22:10:50

Return value from async class method?

Promises have changed my hair color to gray.
And now in more detail.

There is a react application. We will work with the App component and the service . Service - a separate class that is responsible for receiving and, if necessary, transforming data.
There are main conditions: use only class components , requests are made using Apollo(GraphQL).

The service has a method responsible for receiving some data. The method is an asynchronous function. An async function returns a promise .

export default class Service {
  constructor() {
    this._client = new ApolloClient({
      uri: 'http://localhost:4000/',
      cache: new InMemoryCache()
    })
  }

  getCategory = async (id) => {
    let result = await this._client.query({
      query: gql`
        query GetCategories {
          categories {
            name
          }
        }`
    }).then((data) => data.data.categories[id].name)

    return result;
  }
}


In the App component, I am importing a service, instantiating it, and want to use the value that the getCategory method should return. But we all remember that the method returns a promise and not a value, so everyone's favorite [object Promise] is displayed on the screen. And I would like to get the value.

export default class App extends React.Component {
  render() {
    const service = new Service();

    return (
        <Router>
          <div className="app">
            <div className="container">
              <p>{`${service.getCategory(1)}`}</p>
            </div>
          </div>
        </Router>
    );
  }
}


I know perfectly well that for these purposes they write a value to a variable using await, but I can’t do such things in classes. How to proceed in such a situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2022-01-15
@Casufi

In .then you write to the state, you render from the state.
If the application is large, then redux + redux-thunk will help.
And pay attention to the remark from WbICHA to create an instance of a class in the render is more than something, I have a much less cultured word of 6 letters for this.
There is a hell of a lot of asynchronous code in JS and Promise is a great way to manage it, because without it you will have callbacks, their hell and the eternal attempt to shove return into a callback. In theory, after reading about Promises, you should rejoice like a child and sing songs.
https://habr.com/ru/company/vk/blog/269465/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question