Answer the question
In order to leave comments, you need to log in
Is it possible to wait for one asynchronous function to complete and then execute another?
There are two functions that make a request to the server. I need to wait until the first is executed and then the second or synchronously executed and then the second waits until the first is executed.
class UserPage extends Component {
@computed
get user() {
const { match } = this.props;
const userId = parseInt(match.params.id);
return store.getUserById(userId);
}
@computed
get stats() {
this.user.getUserStats();
}
@observable isLoading;
async loadUsersIfNeeded() {
if (this.user === undefined) {
try {
this.isLoading = true;
await store.loadUsers();//вот первая
} finally {
this.isLoading = false;
}
}
}
async loadUserStats() {
const { match } = this.props;
const userId = parseInt(match.params.id);
await this.user.loadStats(userId);//вот вторая(здесь this.user = undefined)
}
componentWillMount() {
this.loadUsersIfNeeded();
//здесь пробовал вставлять вторую,но this.user был undefined т.к. не выполнялась ф-ция выше.
}
render() {
if (this.isLoading) {
return <CircularProgress />;
}
return (
<div className={styles.container}>
<div className={styles.sidebar} key={this.user.id}>
<UserAvatar user={this.user} size={200} />
<div className={styles.usertitleName}>{this.user.name}</div>
</div>
<Table style={{ width: "50%", margin: "25px 0 0 350px" }}>
<TableBody>
<TableRow>
<TableCell style={{ border: "none" }}>Rating</TableCell>
<TableCell style={{ border: "none" }}>
{this.stats.rating}
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{ border: "none" }}>Games</TableCell>
<TableCell style={{ border: "none" }}>
{'this.stats.games'}
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{ border: "none" }}>Wins</TableCell>
<TableCell style={{ border: "none" }}>
{'this.stats.wins'}
</TableCell>
</TableRow>
<TableRow>
<TableCell style={{ border: "none" }}>Defeats</TableCell>
<TableCell style={{ border: "none" }}>
{'this.stats.defeats'}
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
);
}
}
export default observer(UserPage);
Answer the question
In order to leave comments, you need to log in
write the loadAll method
async loadAll(){
this.isLoading = true;
await store.loadUsers();//вот первая
const { match } = this.props;
const userId = parseInt(match.params.id);
await this.user.loadStats(userId);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question