Answer the question
In order to leave comments, you need to log in
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;
}
}
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>
);
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question