反应长轮询异步等待

时间:2020-03-21 09:26:44

标签: reactjs async-await polling

需要向服务器发送请求,直到它返回响应,例如:{tickets:[],stop:true}

这是我的代码,返回未定义:

  getTickets(prevToken) {
    const token = prevToken ? prevToken : await this.getToken();
    const response = await fetch(`https://front-test.beta.aviasales.ru/tickets?searchId=${token}`);

    if (response.ok) {
        let tickets = await response.json();
        return tickets.tickets;
    } else if (response.status == '404') {
        await this.getTickets()
    } else {
        await this.getTickets(token);
    }
  }

  async getToken() {
    const token = await fetch('https://front-test.beta.aviasales.ru/search');
    const tokenId = await token.json();

    return tokenId.searchId;
  }

  async componentDidMount() {
    const tickets = await this.getTickets();

    this.setState(state => ({
      tickets: tickets
    }))
  }

否则,如果我运行这样的代码:

   getTickets(prevToken) {
    const token = prevToken ? prevToken : await this.getToken();
    const response = await fetch(`https://front-test.beta.aviasales.ru/tickets?searchId=${token}`);

    if (response.ok) {
        return tickets.tickets;
    } else {
        await this.getTickets(token);
    }
  }

  async componentDidMount() {
    const tickets = await this.getTickets();

    this.setState(state => ({
      tickets: tickets
    }))
  }

它返回正确的值。如何解决这个问题?

0 个答案:

没有答案