SecDet
@SecDet

Можно ли подождать, пока выполнится одна асинхронная функция, а затем выполнить другую?

Есть две функции выполняющие запрос к серверу. Мне нужно подождать,пока выполнится первая,а затем вторая или синхронно выполнились,а затем вторая ждёт пока выполнится первая.
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);
  • Вопрос задан
  • 277 просмотров
Решения вопроса 1
@afanasiyz
Javascript-разработчик
пишете метод loadAll
async loadAll(){
    this.isLoading = true;
    await store.loadUsers();//вот первая
    const { match } = this.props;
    const userId = parseInt(match.params.id);
    await this.user.loadStats(userId);
}


его вызываете в componentWillMount
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
19 апр. 2024, в 03:52
1000 руб./за проект
19 апр. 2024, в 03:01
1000 руб./за проект
18 апр. 2024, в 21:56
2000 руб./за проект